第一篇:MySql知識點(diǎn)總結(jié)
1.數(shù)據(jù)庫創(chuàng)建 : Create database db_name;
數(shù)據(jù)庫刪除 : Drop database db_name;刪除時可先判斷是否存在,寫成 : drop database if exits db_name.建表 : 創(chuàng)建數(shù)據(jù)表的語法 : create table table_name(字段1 數(shù)據(jù)類型 , 字段2 數(shù)據(jù)類型);
例 : create table mytable(id int , username char(20));
刪表 : drop table table_name;例 : drop table mytable;.添加數(shù)據(jù) : Insert into 表名 [(字段1 , 字段2 , ….)] values(值1 , 值2 , …..);
如果向表中的每個字段都插入一個值,那么前面 [ ] 括號內(nèi)字段名可寫也可不寫
例 : insert into mytable(id,username)values(1,’zhangsan’);.查詢 : 查詢所有數(shù)據(jù) : select * from table_name;
查詢指定字段的數(shù)據(jù) : select 字段1 , 字段2 from table_name;
例 : select id,username from mytable where id=1 order by desc;多表查詢語句------------參照第17條實(shí)例.更新指定數(shù)據(jù) , 更新某一個字段的數(shù)據(jù)(注意,不是更新字段的名字)
Update table_name set 字段名=’新值’ [, 字段2 =’新值’ , …..][where id=id_num] [order by 字段 順序]
例 : update mytable set username=’lisi’ where id=1;
Order語句是查詢的順序 , 如 : order by id desc(或asc), 順序有兩種 : desc倒序(100—1,即從最新數(shù)據(jù)往后查詢),asc(從1-100),Where和order語句也可用于查詢select 與刪除delete.刪除表中的信息 :
刪除整個表中的信息 : delete from table_name;
刪除表中指定條件的語句 : delete from table_name where 條件語句;條件語句如 : id=3;.創(chuàng)建數(shù)據(jù)庫用戶
一次可以創(chuàng)建多個數(shù)據(jù)庫用戶如:
CREATE USER username1 identified BY ‘password’ , username2 IDENTIFIED BY ‘password’…..用戶的權(quán)限控制:grant
庫,表級的權(quán)限控制 : 將某個庫中的某個表的控制權(quán)賦予某個用戶
Grant all ON db_name.table_name TO user_name [ indentified by ‘password’ ];.表結(jié)構(gòu)的修改
(1)增加一個字段格式:
alter table table_name add column(字段名 字段類型);----此方法帶括號
(2)指定字段插入的位置:
alter table table_name add column 字段名 字段類型 after 某字段;
刪除一個字段:
alter table table_name drop字段名;
(3)修改字段名稱/類型
alter table table_name change 舊字段名 新字段名 新字段的類型;
(4)改表的名字
alter table table_name rename to new_table_name;
(5)一次性清空表中的所有數(shù)據(jù)
truncate table table_name;此方法也會使表中的取號器(ID)從1開始.增加主鍵,外鍵,約束,索引。。(使用方法見17實(shí)例)
① 約束(主鍵Primary key、唯一性Unique、非空Not Null)
② 自動增張 auto_increment
③外鍵Foreign key-----與reference table_name(col_name列名)配合使用,建表時單獨(dú)使用
④ 刪除多個表中有關(guān)聯(lián)的數(shù)據(jù)----設(shè)置foreign key 為set null---具體設(shè)置參考幫助文檔.查看數(shù)據(jù)庫當(dāng)前引擎
SHOW CREATE TABLE table_name;
修改數(shù)據(jù)庫引擎
ALTER TABLE table_name ENGINE=MyISAM | InnoDB;.SQL語句運(yùn)用實(shí)例:
--1 建users表
create table users
(id int primary key auto_increment, nikename varchar(20)not null unique, password varchar(100)not null, address varchar(200),reg_date timestamp not null default CURRENT_TIMESTAMP);
--2 建articles表,在建表時設(shè)置外鍵
create table articles(id int primary key auto_increment,content longtext not null,userid int,constraint foreign key(userid)references users(id)on delete set null);
---------
--2.1 建articles表,建表時不設(shè)置外鍵
create table articles(id int primary key auto_increment,content longtext not null,userid int);
--2.2 給articles表設(shè)置外鍵
alter table articles add constraint foreign key(userid)references users(id)on delete set null;
----------
--3.向users表中插入數(shù)據(jù),同時插入多條
insert into
users
(id,nikename,password,address)
values(1,'lyh1','1234',null),(10,'lyh22','4321','湖北武漢'),(null,'lyh333','5678', '北京海淀');
--4.向article中插入三條數(shù)據(jù)
insert
into
articles
(id,content,userid)
values(2,'hahahahahaha',11),(null,'xixixixixix',10),(13,'aiaiaiaiaiaiaiaiaiaiaiaia',1),(14,'hohoahaoaoooooooooo',10);
--5.進(jìn)行多表查詢,選擇users表中ID=10的用戶發(fā)布的所有留言及該用戶的所有信息
select articles.id,articles.content,users.* from users,articles where users.id=10 and articles.userid=users.id order by articles.id desc;
--6.查看數(shù)據(jù)庫引擎類型
show create table users;
--7.修改數(shù)據(jù)庫引擎類型
alter table users engine=MyISAM;---因?yàn)閡sers表中ID被設(shè)置成外鍵,執(zhí)行此句會出錯
--8.同表查詢,已知一個條件的情況下.查詢ID號大于用戶lyh1的ID號的所有用戶
select a.id,a.nikename,a.address from users a,users b where b.nikename='lyh1' and a.id>b.id;
------也可寫成
select id,nikename,address from users where id>(select id from users where nikename='lyh1');
9.顯示年齡比領(lǐng)導(dǎo)還大的員工:
select a.name from users a,users b where a.managerid=b.id and a.age>b.age;
查詢編號為2的發(fā)帖人: 先查articles表,得到發(fā)帖人的編號,再根據(jù)編號查users得到的用戶名。
接著用關(guān)聯(lián)查詢.select * from articles,users得到笛卡兒積,再加order by articles.id以便觀察
使用select * from articles,users where articles.id=2 篩選出2號帖子與每個用戶的組合記錄
再使用select * from articles,users where articles.id=2 and articles.userid=users.id選出users.id等于2號帖的發(fā)帖人id的記錄.只取用戶名:select user where user.id=(select userid from articles where article.id =2)
找出年齡比小王還大的人:假設(shè)小王是28歲,先想找出年齡大于28的人
select * from users where age>(select age from users where name='xiaowang');
*****要查詢的記錄需要參照表里面的其他記錄:
select a.name from users a,users b where b.name='xiaowang' and a.age>b.age
表里的每個用戶都想pk一下.select a.nickname,b.nickname from users a,users b where a.id>b.id;
更保險的語句:select a.nickname,b.nickname from(select * from users order by id)a,(se
lect * from users order by id)b where a.id>b.id;
再查詢某個人發(fā)的所有帖子.select b.* from articles a , articles b where a.id=2 and a.userid=b.userid
說明: 表之間存在著關(guān)系,ER概念的解釋,用access中的示例數(shù)據(jù)庫演示表之間的關(guān)系.只有innodb引擎才支持foreign key,mysql的任何引擎目前都不支持check約束。
第二篇:mySql總結(jié)
Mysql命令:在mysql的bin目錄下執(zhí)行: Mysql –h host_name –u user_name –p password Use 數(shù)據(jù)庫名;選定默認(rèn)數(shù)據(jù)庫(切換數(shù)據(jù)庫)查詢當(dāng)前使用的數(shù)據(jù)庫:select database(); Show databases;顯示所有數(shù)據(jù)庫;
Show tables ;顯示默認(rèn)數(shù)據(jù)庫下的所有表; Show status;顯示服務(wù)器狀態(tài)信息 c;放棄正在輸入的命令; h;顯示命令清單;
s;顯示mysql服務(wù)器狀態(tài)信息; q;退出mysql;
Describe 表名:查看表結(jié)構(gòu);
檔案柜相當(dāng)于數(shù)據(jù)庫,抽屜相當(dāng)于表,抽屜中的文件相當(dāng)于記錄;
0x:加1到9的數(shù)字或者a到f就可以構(gòu)成16進(jìn)制了。注意零x中的x不能大寫。字符串:單引號或者雙引號引起來的都是字符串; Tinyint是1字節(jié); Smallint是2字節(jié); Mediumint是3字節(jié); Int是4字節(jié) Bigint是8字節(jié); 刪除主表前,先刪除子表。選擇主鍵的原則:
1)最少性:盡量選擇單個鍵做為主鍵
2)穩(wěn)定性:盡量選擇數(shù)值更新少的列作為主鍵。查看自定義函數(shù)創(chuàng)建信息:
Show create function function_name;類型總結(jié):
Tinyint :占一個字節(jié),它的范圍是-128到127 Smallint:占2個字節(jié),它的范圍是-2的15次方到2的15次方減一; Mediumint:占3個字節(jié),它的范圍是-2的23次方到2的23次方減一; Int:占4個字節(jié),它的范圍是-2的31次方到2的31次方減一; Bigint:占8個字節(jié),它的范圍是-2的63次方到2的63次方減一; Float:占4個字節(jié) Double:占8個字節(jié)
Decimal(m,n):占m個字節(jié); Char(10)和char(10 char)是一樣的;
數(shù)值列的完整性約束講解:
Auto increment(自動標(biāo)識列):在需要產(chǎn)生唯一標(biāo)示符號或者順序值的時候,可用此屬性。值從1開始,一般在插入null到auto increment列時,mysql會插入比當(dāng)前列最大值大1的值。一個表中最多能有一個此屬性的列。對于想使用此屬性的列應(yīng)該定義為not null,并定義為primary key或者定義為unique。
Null 和not null:默認(rèn)是null,如果在插入數(shù)據(jù)時,指定了not null,那么在插入數(shù)據(jù)時必須要在此字段插入數(shù)據(jù)。如果指定了null ,那么在插入數(shù)據(jù)時,如果沒有給此字段插入數(shù)據(jù),此字段就插入null.mysql-h host-u user-p menagerie 注意,剛才顯示的命令行中的menagerie不是你的 密碼。如果你想要在命令行上在-p選項(xiàng)后提供 密碼,則不能插入空格(例如,如-pmypassword,不是-p mypassword)。但是,不建議在命令行輸入密碼,因?yàn)檫@樣會暴露 密碼,能被在機(jī)器上登錄的其它用戶窺探到。
查詢當(dāng)前日期:使用curdate()函數(shù),任何表都可以的。Select curdate()from cjym;可以通過year,month,day獲取它的年月日。Select year(curdate())from cjym;Select month(curdate())from cjym;Select day(curdate())from cjym;Mysql中的_和%表示單個字符和零個或者多個字符; 有l(wèi)ike 和not like比較操作符;
要想找出你的服務(wù)器支持哪個存儲引擎,執(zhí)行下面的語句: Show engines;Select 1/7;都可以; 日期和時間類型: Time :時間; Date:日期;
Datetime:日期和時間; 創(chuàng)建表:
Create table student(Student_id int(10)not null primary key auto_increment, Student_name varchar(20));注意在創(chuàng)建表的時候,如果是手動寫sql語句的時候自動標(biāo)示符要寫這樣的 auto_increment;有個下劃線; 更改表結(jié)構(gòu)操作:
給表添加一條字段:在最前面加字段用first,在最后面加用after;默認(rèn)在最后加; Alter table student add age int first;給表設(shè)定默認(rèn)值:
Alter table student alter column_name set default default_value;給表中的字段添加主鍵;如果主鍵存在則出現(xiàn)錯誤; Alter table student add primary key(column_name);刪除表中的一列:
Alter table student drop column_name;刪除表中的主鍵: Alter table student drop primary key;更改表的名字:
Alter table student rename as new_tablename;修改表中的字段類型: Alter table student modify sno int;運(yùn)算符:
Between。。and用于檢驗(yàn)一個值(一個求值表達(dá)式)是否存在一個指定的范圍內(nèi);
Select 10 between 1 and 100;結(jié)果是1:表示是真的;
In 用于檢驗(yàn)一個值(一個表達(dá)式)是否包含在一個指定的集合中。
Select 2 in(1,2,3,4,5,6),’a’ in(‘b’,’e’,.’h’);結(jié)果顯示1和0;1表示真,0表示假;
Is null和is not null來測定是否為空;
特殊的運(yùn)算符:<=>:mysql稱它為null安全的等于; Select null=null,null< = >null;結(jié)果顯示null和1; Regexp運(yùn)算符; Mysql中的元字符;
邏輯運(yùn)算符:and(&&),or(||),not(!)插入數(shù)據(jù)時,插入多行值時:
插入多行數(shù)據(jù): Insert into 表名(列名)Select 列名 From 表名;
更改記錄的操作語法格式:
Update 表名 set 列名=更新值 [where 更新條件] 刪除記錄的操作格式:
Delete from 表名 [where 刪除條件]; 表和字段的引用方式有兩種: 絕對引用:數(shù)據(jù)庫名.表名(.字段名);相對引用:表名.(字段名); Where子句使用的謂詞:
Between。。and。。在兩數(shù)之間 Not between ….and ….不在兩數(shù)之間 In:是否在特定的集合里。Not in :與上面相反。Like:是否匹配一個模式;
Regexp:檢查一個值是否匹配一個常規(guī)表達(dá)式; 復(fù)制表:
Create table student select name,age from stu;復(fù)制表后,表中的字段和stu表中的字段一樣并且記錄數(shù)也是存在的;
學(xué)習(xí)地址:http://
Mysql的存儲過程: Create procedure p()Begin End;
delimiter //
create procedure math_demo()begin
declare i int default 0;
declare d decimal(10,4)default 0;
declare f float default 0;
while i < 10000 do
set d = d +.0001;
set f = f +.0001E0;
set i = i + 1;
end while;
select d,f;end // call math_demo();
mysql中的自定義方法的使用 delimiter // create function function_name()returns return_type;begin
end;// 執(zhí)行mysql自定義的函數(shù)用 Select function_name();
#mysql中的存儲過程 delimiter //
create procedure math_demo()begin
declare i int default 0;
declare d decimal(10,4)default 0;…….return return_value;
declare f float default 0;
while i < 10000 do
set d = d +.0001;
set f = f +.0001E0;
set i = i + 1;
end while;
select d,f;end // call math_demo();// delimiter // create function xiaoxiao()returns int begin return 2;end;// #在mysql中創(chuàng)建的自定義函數(shù)要加的delimiter,都要一次性選中執(zhí)行。每條語句都要用分號結(jié)束。delimiter // create function xiaoxiao1()returns int begin return 2;end // #執(zhí)行mysql中的自定義函數(shù) select xiaoxiao1();
根據(jù)一個布爾值來檢驗(yàn)一個值,在這里布爾值可以是true,false,unknown;
運(yùn)算符: 等號:=,<=>,不等號:!=,<>;賦值號::=;? XOR
邏輯XOR。當(dāng)任意一個操作數(shù)為 NULL時,返回值為NULL。對于非 NULL 的操作數(shù),假如一個奇數(shù)操作數(shù)為非零值,則計算所得結(jié)果為 1,否則為 0。
a XOR b 的計算等同于(a AND(NOT b))OR((NOT a)和 b)。
Coalesce();函數(shù)的使用方法:
返回值為列表中第一非null值,在沒有非null值的情況下返回null。
Greatest();函數(shù)的使用及功能說明:
當(dāng)函數(shù)有2個或者2個以上的參數(shù)時,返回參數(shù)中的最大參數(shù)值,比較參數(shù)所依據(jù)的規(guī)律同least()函數(shù)相同。
Interval();函數(shù)的使用及功能說明: INTERVAL(N,N1,N2,N3,...)
假如N < N1,則返回值為0;假如N < N2 等等,則返回值為1;假如N 為NULL,則返回值為-1。所有的參數(shù)均按照整數(shù)處理。為了這個函數(shù)的正確運(yùn)行,必須滿足 N1 < N2 < N3 < ……< Nn。其原因是使用了二分查找(極快速)。
Least();函數(shù)的使用及功能說明: · LEAST(value1,value2,...)
在有兩個或多個參數(shù)的情況下,返回值為最小(最小值)參數(shù)。用一下規(guī)則將自變量進(jìn)行對比:
o 假如返回值被用在一個 INTEGER 語境中,或是所有參數(shù)均為整數(shù)值,則將其作為整數(shù)值進(jìn)行比較。
假如返回值被用在一個 REAL語境中,或所有參數(shù)均為實(shí)值,則 將其作為實(shí)值進(jìn)行比較。
o 假如任意一個參數(shù)是一個區(qū)分大小寫的字符串,則將參數(shù)按照區(qū)分大小寫的字符串進(jìn)行比較。
o 在其它情況下,將參數(shù)作為區(qū)分大小寫的字符串進(jìn)行比較。o
假如任意一個自變量為NULL,則 LEAST()的返回值為NULL。
二,控制流函數(shù) Case的使用: 格式1: Case value
when [compare_value] then result_value when [compare_value2] then result_value2 else result_value3 end
格式2: case when value=[compare_value1] then result_value else result_value2 end
? IF(expr1,expr2,expr3)
如果 expr1 是TRUE(expr1 <> 0 and expr1 <> NULL),則 IF()的返回值為expr2;否則返回值則為 expr3。IF()的返回值為數(shù)字值或字符串值,具體情況視其所在語境而定。
ASCII()函數(shù)查看對應(yīng)符號的ascii碼。
第三篇:計算機(jī)二級《MySQL數(shù)據(jù)庫程序設(shè)計》知識點(diǎn)總結(jié)
MySQL知識點(diǎn)總結(jié)
.數(shù)據(jù)操作:檢索、排序、過濾、分組、匯總、計算、聯(lián)接、子查詢與組合查詢.表操作:表的創(chuàng)建、修改、刪除和重命名、表數(shù)據(jù)的插入、更新和刪除.索引(含主、外鍵)、視圖
.難度編程:存儲過程與存儲函數(shù)、觸發(fā)器與事件、PHP.數(shù)據(jù)庫管理:事務(wù)處理、用戶與權(quán)限、備份與還原、數(shù)據(jù)庫維護(hù)
1.檢索數(shù)據(jù):select?from?
Select [distinct] prod_id,prod_name from products [limit 4,5];2.檢索排序:order by?
Select * from products order by prod_id [asc|desc],prod_name [asc|desc];3.過濾數(shù)據(jù):where 字句
= <>!= >>= <<= between(1)普通where 字句
Select prod_id,prod_name from products where prod_name=’liyang’;Select prod_id,prod_name from products where prod_id between 10 and 50;Select prod_id,prod_name from products where prod_name is [not] null;(2)組合where字句:使用AND和OR連接多個條件表達(dá)式,且AND次序優(yōu)于OR;(3)IN 與NOT操作符
Select prod_id,prod_name from products where prod_id [not] in(1,2,3)|prod_name in(’zhangsan’,’lisi’,’wangwu’);(4)LIKE操作符與通配符:“%”與“_”
Select prod_id,prod_name from products where prod_name like ’%liu%’;Select prod_id,prod_name from products where prod_name like ’_u%’;找出u位于名字的第二個位置的prod_id和prod_name。(5)正則表達(dá)式 4.計算字段
(1)拼接字段:concat(?,?)Select concat(姓氏,名字)as 姓名 from orders;Select concat(vend_name,’(’,vend_country,’)’)from vendors;(2)算術(shù)運(yùn)算
Select prod_name,prod_price,prod_num,prod_price*prod_num as prod_money from products;4.使用數(shù)據(jù)處理函數(shù):文本處理函數(shù)、日期和時間處理函數(shù)、數(shù)值處理函數(shù)。5.匯總數(shù)據(jù):聚集函數(shù) SUM()AVG()COUNT()MAX()MIN()Select avg(distinct prod_price)from products;Select avg(prod_price)均價,max(prod_price)最高價 from products;6.分組數(shù)據(jù):group by? 創(chuàng)建分組、過濾分組、分組排序
Select count(prod_id),prod_id from products where prod_id>1000 group by prod_id having count(prod_id)>2 order by prod_id;求出prod_id大于1000且產(chǎn)品數(shù)量大于2的產(chǎn)品數(shù)量,并按prod_id排序,注意分組語句中對象要前后一致,如下劃線部分。7.使用子查詢:進(jìn)行過濾select?where?in(select?where?in(select?))、作為計算字段使用子查詢。8.聯(lián)接:join?on?(1)普通聯(lián)接
Select oi.order_num,oi.prod_id,p.prod_name,p.vend_id,v.vend_name from orderitems oi join products p on oi.prod_id=p.prod_id join vendors v on p.vend_id=v.vend_id where vend_name=’liyang’;可同時聯(lián)接多個表且可同時用于數(shù)據(jù)過濾,這種類型的聯(lián)接一般為內(nèi)部聯(lián)接。
(2)自聯(lián)接:一個表自己與自己聯(lián)接,注意判斷好各字段與前后兩個表的關(guān)系。(3)自然聯(lián)接:基本上簡歷的內(nèi)部聯(lián)接都是自然聯(lián)接。
(4)外部聯(lián)接:在關(guān)系表中沒有關(guān)聯(lián)的信息的行也能顯示出來的聯(lián)接,根據(jù)表在join字句的左邊還是右邊可分為左聯(lián)接與右聯(lián)接。(5)帶聚集函數(shù)的聯(lián)接
Select c.cust_id,count(o.order_num)num_ord from customers c join orders o on c.cust_id=o.cust_id order by c.cust_id;找出客戶對應(yīng)的訂單數(shù)。
9.組合查詢:連接多個(至少兩個)查詢語句,滿足其中一個查詢語句條件的結(jié)果都會顯示出來 union(不重復(fù)顯示)/union all(可重復(fù)顯示即全部顯示)Select vend_id,prod_id,prod_price from products where prod_price<=5 Union [all] Select vend_id,prod_id,prod_price from products where vend_id in(1001,1002)order by prod_id;注意每個查詢必須包含相同的列、表達(dá)式或者聚集函數(shù),列的數(shù)據(jù)類型必須兼容,排序語句只能放在最后面,該排序語句對組合查詢語句中的所有select語句都適用。10.全文本搜索:只支持引擎為MyISAM的表,不支持引擎為InnoDB的表,可對搜索結(jié)果進(jìn)行智能排序后輸出,具有較高等級的行先返回。
Match(全文本搜索字段)against(’全文本搜索內(nèi)容’[with query expansion])其中下劃線部分為拓展語句,使用該語句,除了可以返回符合所設(shè)置的“全文本搜索內(nèi)容”的數(shù)據(jù)結(jié)果,還可返回與“全文本搜索內(nèi)容”有較高相似度的數(shù)據(jù)結(jié)果。(1)啟用全文本搜索支持
Create table fs(id int not null primary key,c text,c1 text,fulltext(c,c1))engine=MyISAM;(2)進(jìn)行全文本搜索
Select note_text from productnotes where match(note_text)against(’liyang’ with query expansion);11.插入數(shù)據(jù):insert into?{values|select}?
Insert into products(prod_id,prod_name,prod_price)values(1,’豆?jié){’,2),(3,’雞蛋’,1);可同時插入多行數(shù)據(jù)。
Insert into products(prod_id,prod_name,prod_price)select vend_id,vend_name, vend_price from vendors where vend_id<=10;12.更新數(shù)據(jù):update [ignore]?set?,一般情況下,若更新的數(shù)據(jù)中有部分?jǐn)?shù)據(jù)出錯,則全部數(shù)據(jù)返回到原來的數(shù)據(jù),而ignore的作用在于即使更新的數(shù)據(jù)中出現(xiàn)錯誤,只對出現(xiàn)錯誤的數(shù)據(jù)返回到原來數(shù)據(jù),而未出現(xiàn)錯誤的數(shù)據(jù)返回更新后的結(jié)果實(shí)現(xiàn)更新。update products set prod_name='饅頭',prod_price=1 where prod_id=1;update customers set cust_city=concat(cust_city,’市’)| cust_city =replace(cust_city,’市’,’city’)where cust_id>1000;13.刪除數(shù)據(jù):delete from? Delete from products where prod_id between 10 an 50;14.表的相關(guān)操作
(1)創(chuàng)建表:對表結(jié)構(gòu)進(jìn)行設(shè)置create table?
Create table products(prod_id int null auto_increment primary key,prod_name varchar(50),prod_price int,prod_city varchar(50)default ’廣州’)engine= InnoDB;每個字段名后需要設(shè)置數(shù)據(jù)類型,default為指定默認(rèn)值,只支持常量不支持函數(shù),且只在插入數(shù)據(jù)時起作用而在更新數(shù)據(jù)時不起作用,InnoDB是一個可靠的事務(wù)處理引擎,但不支持全文本搜索。
(2)更新表:對表結(jié)構(gòu)進(jìn)行修改 alter table {add|drop}?
Alter table products add prod_city varchar(50); Alter table products drop prod_price;(3)刪除表:一旦刪除,無法撤銷 drop table?
Drop table products;(4)重命名表:rename table?to?
Rename table products to new_products;15.索引的相關(guān)操作
(1)創(chuàng)建索引:常用于數(shù)據(jù)的快速檢索,MySQL中,常用索引在物理可分為:BTREE、HASH索引兩類;在具體用途上可分為:INDEX、UNIQUE、PRIMARY KEY、FOREIGN KEY、FULL TEXT、SPATIAL等。
1使用create index 語句創(chuàng)建索引,對已存在的表創(chuàng)建索引 ○Create [unique|fulltext|spatial] index index_name [using BTREE|HASH] on tbl_name(index_col_name[,index_col_name?]);Create unique index index_products on products(prod_name(2)desc,prod_price);2使用create table 語句創(chuàng)建索引,創(chuàng)建表的同時創(chuàng)建索引 ○Create table seller(seller_id int not null auto_increment,seller_name char(50),seller_adress char(50),seller_contact char(50),product_type int,sales int,primary key(seller_id,product_type),[unique|fulltext|spatial] index index_seller(sales));3使用alter table語句創(chuàng)建索引,修改表的同時添加索引 ○Alter table tbl_name add {[unique|fulltext|spatial] index index_tbl_name(字段名)|primary key(字段名)|foreign key(字段名)references elsetbl_name(相同字段名)};(2)查看索引:Show index from tbl_name [where expr];(3)刪除索引:drop index index_nameon tbl_name語句或alter table語句
Drop index index_name on tbl_name;Alter table tbl_name drop {[unique|fulltext|spatial] index index_tbl_name(字段名)|primary key(字段名)|foreign key(字段名)references elsetbl_name(相同字段名};(下劃線部分不確定)16.視圖的相關(guān)操作
視圖:虛擬的表,視圖本身不包含表中的列和數(shù)據(jù),它包含只是一個SQL查詢,常用于 檢索數(shù)據(jù)。*視圖的作用與規(guī)則。(1)創(chuàng)建視圖:Create view view_name as select?[where?];Create view view_products as select prod_id,prod_name,prod_price,prod_num, prod_price*prod_num as prod_money from products where prod_id<=10 [with check option];--下劃線部分表示今后對該視圖數(shù)據(jù)的修改都必須符合prod_id<=10(2)查看視圖(用法同表): select * from view_name;(3)刪除視圖:drop view view_name;17.完整性:實(shí)體完整性(主鍵與候選鍵)、參照完整性(主鍵與外鍵)、用戶定義的完整性(非空約束與check約束)。
18.創(chuàng)建主鍵約束:create table語句或alter table語句
Create table products(prod_id int not null auto_increment primary key,c int);作為列的主鍵約束;
Create table products(prod_id int not null auto_increment,c int,c1 int,primary key(prod_id));作為表的主鍵約束,且復(fù)合主鍵職能用這種形式創(chuàng)建 Alter table products add primary key(prod_id);備注:實(shí)體完整性通過主鍵約束與候選鍵約束來實(shí)現(xiàn),候選鍵約束的創(chuàng)建類似主鍵約束的創(chuàng)建,實(shí)質(zhì)上同索引。
19.設(shè)置表外鍵:create table語句或alter table語句,外鍵中列的數(shù)目和數(shù)據(jù)類型必須與被參照表的主鍵中列的數(shù)目和對應(yīng)數(shù)據(jù)類型一致。
alter table tbl_name add [constraint fk_name] foreign key(?)references? Create table products(prod_id int not null auto_increment,c int,c1 int,foreign key(prod_id)references customers(prod_id));alter table products add constraint fk_products_cust foreign key(cust_id)references cust(cust_id);20.存儲過程:為了以后的使用而保存的一條或多條SQL語句的集合
--建立存儲過程:建立一個可通過輸入item_id,輸出對應(yīng)訂單總金額的存儲過程->Delimiter //--改變分割符為//->create procedure ordertotal(in o_id int,out o_total decimal(10,2))過程名字輸入?yún)?shù)及類型輸出參數(shù)及類型->begin->select sum(item_price*item_num)from orderitems where item_id=o_id into o_total;->if o_total is null then->select ’不存在該訂單號’;->end if;->end;->//--執(zhí)行存儲過程:當(dāng)item_id=200005時,得出對應(yīng)訂單總金額->delimiter;--將分割符改回分號->call ordertotal(200005,@total);--由于不存在輸出參數(shù),故定義一個輸出變量,變量必須用@開頭->select @total;返回結(jié)果為149.87 備注:書本第十一章后的編程題,使用update語句,兩個參數(shù)類型都需要為in。--顯示存儲過程->Show create procedure ordertotal;--刪除存儲過程
->Drop procedure ordertotal;21.存儲函數(shù)
存儲函數(shù)與存儲過程的區(qū)別:.存儲函數(shù)不能擁有輸出參數(shù);.存儲函數(shù)可直接調(diào)用,且不需使用call語句,而存儲過程的調(diào)用必須使用call語句;.存儲函數(shù)中必須包含一條return語句,而這條特殊的SQL語句不允許包含于存儲過程。--建立存儲函數(shù):根據(jù)給定的cust_id返回客戶所在的州名(縮寫),若庫中無給定的cust_id,則返回“不存在該客戶”。->delimiter //->create function fn_search(c_id int)->returns varchar(50)--定義返回的數(shù)據(jù)類型,與函數(shù)部分中的數(shù)據(jù)類型需統(tǒng)一,如函數(shù)中的“不存在該客戶”為6個字符,如果這里設(shè)置為char(5),則無法輸出該結(jié)果->deterministic– 表示對于相同的輸入值,返回值也相同->begin->declare state char(2);--聲明一個變量state,作為輸出的州變量->select cust_state from customers where cust_id=c_id into state;->if state is null then->return(select ’不存在該客戶’);--注意這里return不用加s->else->return(select state);->end if;->end;->//--執(zhí)行存儲函數(shù)
->select fn_search(10001);--刪除存儲函數(shù)
->drop function fn_search;--刪除前要確定該函數(shù)無依賴關(guān)系,即不存在其他存儲過程或存儲函數(shù)調(diào)用過該存儲函數(shù)。
22.觸發(fā)器:MySQL響應(yīng)insert、delete、update語句時自動執(zhí)行的一條MySQL語句,創(chuàng)建觸發(fā)器時需要給出的4條信息:唯一的觸發(fā)器名、觸發(fā)器相關(guān)的表、觸發(fā)器應(yīng)該響應(yīng)的活動(insert delete、update)、觸發(fā)器何時執(zhí)行(處理前或處理后)。
(1)insert觸發(fā)器:當(dāng)對表插入數(shù)據(jù)時起作用,含有一個虛擬表New,可訪問增加的行,只能用after--建立一個insert觸發(fā)器,用于記錄insert語句操作時的系統(tǒng)時間和插入的order_num->delimiter //->create trigger trg_order_insert after insert on orders for each row 觸發(fā)器 觸發(fā)器名 執(zhí)行時間 相關(guān)表->begin->insert into order_log(o_date,order_num)values(now(),new.order_num);--order_log是事先建立好的表,用于記錄insert語句操作時的系統(tǒng)時間和插入的order_num->end;->//--執(zhí)行insert觸發(fā)器->delimiter;->insert into orders(order_date,cust_id)values(’2010-9-15’,10001);--由于order_num是自動遞增的,故在這里不作為插入對象(2)delete觸發(fā)器:當(dāng)對表刪除數(shù)據(jù)時起作用,含有一個虛擬表Old,可訪問被刪除的行,只能用after,創(chuàng)建方法與insert類似,區(qū)別在于delete和old--建立一個delete觸發(fā)器,用于記錄delete語句操作時的系統(tǒng)時間和刪除的order_num->delimiter //->create trigger trg_order_delete after delete on orders for each row 觸發(fā)器 觸發(fā)器名 執(zhí)行時間 相關(guān)表->begin->insert into order_log(o_date,order_num)values(now(),old.order_num);--order_log是事先建立好的表,用于記錄delete語句操作時的系統(tǒng)時間和刪除的order_num->end;->//--執(zhí)行delete觸發(fā)器->delimiter;->delete from orders where order_num=20010;(3)update觸發(fā)器:當(dāng)對表修改數(shù)據(jù)時起作用,同時含有new和old兩個虛擬表。結(jié)合New可訪問更新行的記錄;結(jié)合old可訪問更新前行的記錄,可用after,也可用before。1用after ○--建立一個update觸發(fā)器,用于記錄update語句操作時的系統(tǒng)時間和更新數(shù)據(jù)的order_num->delimiter //->create trigger trg_order_update after update on orders for each row 觸發(fā)器 觸發(fā)器名 執(zhí)行時間 相關(guān)表->begin->insert into order_log(o_date,order_num)values(now(),old.order_num);->end;->//--執(zhí)行update觸發(fā)器->delimiter;->update orders set order_date=’2015-9-18’ where cust_id=10001;2用before ○--建立一個update觸發(fā)器,如果更新后的prod_price大于原來的1.2倍,則用原來的1.2倍作為當(dāng)前價格->delimiter //->create trigger trg_order_update before update on orders for each row 觸發(fā)器 觸發(fā)器名 執(zhí)行時間 相關(guān)表->begin->if new.prod_price>old.prod_price*1.2 then->set new.prod_price=old.prod_price*1.2;->end if;->end;->//(4)刪除觸發(fā)器:drop trigger trg_name;23.事件:臨時觸發(fā)器,要使用事件調(diào)度器,必須開啟“event_scheduler”.查看:show variables like ’event_scheduler’;.開啟:set global event_scheduler=1;(1)創(chuàng)建事件
CREATE EVENT EVENT_NAME ON SCHEDULE schedule DO event_body;其中schedule的語法格式為
AT timestamp [+INTERVAL interval]?|every interval--指定事件執(zhí)行的時間,可以為某時刻點(diǎn)即timestamp,或某時刻點(diǎn)開始的interval時間后,或者為每隔interval時間執(zhí)行一次
[starts timestamp [+INTERVAL interval]]--設(shè)置事件開始執(zhí)行的時間 [ends timestamp [+INTERVAL interval]]--設(shè)置事件終止執(zhí)行的時間
--建立一個事件,用于每個月向customers表中插入一條數(shù)據(jù)“l(fā)iyang、廣州”,該事件從下個月開始并于2015-12-31結(jié)束->delimiter //->create event event_insert on schedule every 1 month->starts curdate()+interval 1 month->ends ’2015-12-31’->do->begin->if year(curdate())<2015 then->insert into customers(cust_name,cust_adress)values(’liyang’,’廣州’);->end if;->end;->//(2)修改事件,用于修改時間的狀態(tài):alter event event_name{enable|disable};(3)刪除事件:drop event event_name;24.管理實(shí)務(wù)處理:start transaction?
實(shí)務(wù)處理的術(shù)語:
(1)實(shí)務(wù)(transaction):一組SQL語句;(2)回退(rollback):撤銷指定SQL語句的過程;(3)提交(commit):指定未存儲的SQL語句結(jié)果寫入到數(shù)據(jù)庫表里,提交后無法回退;(4)保留點(diǎn)(savepoint):實(shí)務(wù)處理中設(shè)置的臨時占位符。
25.安全管理(用戶創(chuàng)建修改與刪除以及用戶權(quán)限的查看設(shè)置與撤銷)(1)創(chuàng)建用戶賬號:create user ben identified by ’ben’;(2)修改用戶賬號:update mysql.user set user=’new_ben’ where user=’ben’;--從mysql數(shù)據(jù)庫中的用戶表user進(jìn)行修改(3)查看訪問權(quán)限:show grants for new_ben;(4)設(shè)置訪問權(quán)限:grant?to?.grant {all|select,update,delete,insert}on {*.*|crashcourse.*|crashcourse.cus tomers} to new_ben;.grant select(cust_id,cust_name)on crashcourse.customers to new_ben;--可針對{整個服務(wù)器|整個數(shù)據(jù)庫|數(shù)據(jù)庫中某個表|數(shù)據(jù)庫中某個表的某些字段},對用戶同時設(shè)置全部或一種或多種權(quán)限
(5)撤銷訪問權(quán)限:revoke?from?,用法與grant?to?類似(6)更改口令(密碼)
Set password for new_ben=password(’new_ben’);(7)刪除用戶:drop user new_ben;26.數(shù)據(jù)庫備份與還原.使用SQL語句
backup table tbl_name to?/restore table tbl_name from?(只用于MyISAM表)select?intooutfile?/load data?infile?into table tlb_name.使用命令行實(shí)用程序:mysqlhotcopy(只用于MyISAM表)或mysqldump/mysql(1)使用select?intooutfile?/load data?infile?into table tlb_name.備份數(shù)據(jù):
Select * from mysql.products into outfile ’d:products.txt’ [Fields terminated by ’,’ optionally enclosed by ’”’
lines terminated by ’nr’;--定義字段間的分割符、字符型數(shù)據(jù)的存放形式、行與行之間的分割符.恢復(fù)數(shù)據(jù)
Load data infile ’d:products.txt’into table customers.copy [Fields terminated by ’,’ optionally enclosed by ’”’
lines terminated by ’nr’;--必須與備份時一致(2)使用命令行實(shí)用程序mysqldump/mysql(文本形式)
進(jìn)入cmd運(yùn)行界面(mysqldump—help 可用于獲取mysqldump的選項(xiàng)表及更多幫助信息).備份整個數(shù)據(jù)庫服務(wù)器、或整個數(shù)據(jù)庫或數(shù)據(jù)庫中某個表
Mysqldump –u root –proot –P 3306 –h localhost {all-databases|mysql_test [products]}>d:data.sql.恢復(fù)數(shù)據(jù)
Mysql –u root –proot –P 3306 –h localhost {all-databases|mysql_test [products]} (1)analyze table tbl_name;更新表的索引散列程度,檢查表鍵是否正確(2)check table tbl_name;檢查一個或多個表是否有錯誤 (3)checksum table tbl_name;對數(shù)據(jù)庫中的表進(jìn)行校驗(yàn),保證數(shù)據(jù)的一致性 (4)optimize table tbl_name;利用表中未使用的空間并整理數(shù)據(jù)文件碎片,保證數(shù)據(jù)讀取效率 (5)repair table tbl_name;修復(fù)一個或多個可能被損害的MyISAM表 28.二進(jìn)制日志文件的使用:mysqlbinlog 29.使用PHP進(jìn)行MySQL數(shù)據(jù)庫編程 編程步驟: .首先建立與MySQL數(shù)據(jù)庫服務(wù)器的連接;.然后選擇要對其進(jìn)行操作的數(shù)據(jù)庫; .再執(zhí)行相應(yīng)的數(shù)據(jù)庫操作,包括對數(shù)據(jù)的添加、刪除、修改和查詢等;.最后關(guān)閉與MySQL數(shù)據(jù)庫服務(wù)器的連接。(1)數(shù)據(jù)庫服務(wù)器連接、選擇數(shù)據(jù)庫 .使用mysql_connect()建立非持久連接 Php $con=mysql_connect(“l(fā)ocalhost:3306”,“root”,“123456”);if(!$con){ echo “數(shù)據(jù)庫服務(wù)器連接失??! .使用mysql_pconnect()建立持久連接 ”;echo “用戶名:root .使用mysql_select_db(databases[,connection])選擇數(shù)據(jù)庫 ”;die();} mysql_select_db(“mysql_test”,$con);if(mysql_errno()){ echo “數(shù)據(jù)庫選擇失?。?br>”;die();} echo “數(shù)據(jù)庫選擇成功! /*向數(shù)據(jù)庫mysql_test中的表customers添加一個名為“李中華”的客戶的全部信息*/ ”);Mysql_select_db(“mysql_test”,$con)or die(“數(shù)據(jù)庫選擇失??! $sql=“insert into customers(’cust_id’,’cust_name’,’cust_sex’)”;$sql=$sql.“values(null,’李中華’,’M’)”;if(mysql_query($sql,$con))echo “客戶信息添加成功! .數(shù)據(jù)的更新 /*將數(shù)據(jù)庫mysql_test的表customers中的一個名為“李中華”的客戶的地址修改為“廣州市”*/ ”);Mysql_select_db(“mysql_test”,$con)or die(“數(shù)據(jù)庫選擇失??! .數(shù)據(jù)的刪除 /*將數(shù)據(jù)庫mysql_test的表customers中一個名為“李中華”的客戶信息刪除*/ ”);Mysql_select_db(“mysql_test”,$con)or die(“數(shù)據(jù)庫選擇失??! (3)數(shù)據(jù)庫的查詢 .使用mysql_fetch_array(data[,array_type])讀取結(jié)果集中的記錄 /*在數(shù)據(jù)庫mysql_test的表customers中查詢cust_id為916的客戶的姓名*/ ”);Mysql_select_db(“mysql_test”,$con)or die(“數(shù)據(jù)庫選擇失?。?br>”);Mysql_query(“set names ’gbk’”);$sql=“select cust_name from customers”;$sql=$sql.“where cust_id=916”;$result=mysql_query($sql,$con);if($result){ echo “客戶查詢成功! .使用mysql_num_rows(data)讀取結(jié)果集中的記錄數(shù) /*在數(shù)據(jù)庫mysql_test的表customers中查詢女性客戶的人數(shù)*/ ”);Mysql_select_db(“mysql_test”,$con)or die(“數(shù)據(jù)庫選擇失??! MySql問題解決總結(jié) ERROR 1045(28000): Access denied for user 'root'@'localhost'(using password: YES)ERROR 1045(28000): Access denied for user 'root'@'localhost'(using password: NO) 這種問題就是mysql密碼需要重置; 重置方式: 1.打開/etc/mysql/debian.cnf文件,里面存儲了相關(guān)的密碼,我的文件信息如下 sudovi /etc/mysql/debian.cnf# Automatically generated for Debian scripts.DO NOT TOUCH![client] host = localhost user = debian-sys-maint password = 6x1XG2B5p75WtFV2 socket = /var/run/mysqld/mysqld.sock [mysql_upgrade] host = localhost user = debian-sys-maint password = 6x1XG2B5p75WtFV2 socket = /var/run/mysqld/mysqld.sock basedir = /usr 在[client]段有user=以及password=這兩行,這就是通過apt-get安裝mysql,系統(tǒng)給我們設(shè)置的mysql登錄名和密碼 2.輸入命令: mysql-udebian-sys-maint-pdebian-sys-maint即debian.cnf中user=后面的內(nèi)容.回車后會提示輸入密碼,此時把password=后面的內(nèi)容復(fù)制粘貼后回車即可進(jìn)行mysql 控制臺 3.進(jìn)入控制臺后.按以下步驟進(jìn)行: use mysql;update user set password=PASSWORD('新密碼')where user='root';FLUSH PRIVILEGES;此時可以輸入quit;退出后用root帳號登錄,也可以繼續(xù)其他操作. 查詢(R)Selec子句 書寫順序 Select distinct:要返回的列或表達(dá)式 From:從中檢索數(shù)據(jù)的表 Where:行級過濾/分組前過濾 group by:分組說明 having:組級過濾/分組后過濾 order by:輸出排序順序desc/asc limit start, count:要檢索的行數(shù) limit 3,4 從第3行開始的連續(xù)4行 SELECT order_num,sum(quantity*item_price)ordertotal FROM orderitems WHEREorder_numBETWEEN20005AND 20009GROUP BY order_num HAVINGsum(quantity*item_price)>=50ORDER BYordertotalDESCLIMIT4;執(zhí)行順序 From表名->inner/left/right/ join on->where->group by->select distinct *->having->order by->limit start, count 插入Insert into(C)INSERT INTO students(name)values(‘楊過’),(‘小龍女’);更新(U)Update UPDATE customers SETcust_email = ‘elmer@fudd.com’WHEREcust_id = 10005;刪除(D)Delete DELETE FROM customers WHEREcust_id = 10006;Truncate刪除原來的表并重新創(chuàng)建一個表,刪除標(biāo)的全部內(nèi)容時效率高。 操作表 創(chuàng)建CREATE TABLE customers(Cust_idint not null auto_increment primary key,Cust_name char(50)not null,Cust_addresschar(50)null)engine = innoDB;更新ALTER TABLE刪除DROP TABLEcustomers2;重命名RENAME TABLE customers2 TO customers;操作數(shù)據(jù)庫 創(chuàng)建CREATE DATABASE xxx charset = utf8;刪除DROP DATABASEXXX;切換USE XXX;查看SHOW DATABASES;關(guān)聯(lián)查詢 INNER/LEFT/RIGHTJOIN ON SELECT students.name,subjects.title,scores.scoreFROM scores INNER JOIN students ONscores.stuid = students.id INNER JOIN subjects ONscores.subid = subjects.id;
”;die();} echo “數(shù)據(jù)庫服務(wù)器連接成功!
”;?> //將connect.php部署在已開啟的WAMP平臺環(huán)境中,并在瀏覽器地址中輸入“http://localhost/connect.php”
”;echo “使用函數(shù)mysql_pconnect()永久連接數(shù)據(jù)庫。
”;?>
” ?>(2)數(shù)據(jù)的添加、更新和刪除操作,mysql_query(SQL語句[,connection]),insert、update、delete語句可置于函數(shù)mysql_query()中從而實(shí)現(xiàn)數(shù)據(jù)的添加、更新和刪除操作.數(shù)據(jù)的添加
”);Mysql_query(“set names ’gbk’”);//設(shè)置中文字符集
”;else echo “客戶信息添加失??!
”;?>
”);Mysql_query(“set names ’gbk’”);$sql=“update customers set cust_address=’廣州市’”;$sql=$sql.“where cust_name=’李中華’”;if(mysql_query($sql,$con))echo “客戶地址修改成功!
”;else echo “客戶地址修改失敗!
”;?>
”);Mysql_query(“set names ’gbk’”);$sql=“delete from customers”;$sql=$sql.“where cust_name=’李中華’”;if(mysql_query($sql,$con))echo(“客戶信息刪除成功!
”);else echo(“客戶信息刪除失敗!
”);?>
”;$array=mysql_fetch_array($result,MYSQL_NUM);if($array){ echo “讀取到客戶信息!
”;echo “所要查詢客戶的姓名為:”.$array[0].“
”;} else echo “未讀取到客戶信息!
”;} else echo “客戶查詢失?。?br>”;?>
”);Mysql_query(“set names ’gbk’”);$sql=“select * from customers”;$sql=$sql.“where cust_sex=’F’”;$result=mysql_query($sql,$con);if($result){ echo “查詢成功!
”;$num=mysql_num_rows($result);//如果結(jié)果為空,則為0行 echo “所要查詢的女性客戶人數(shù)為:”.$num.“位
”;} else echo “查詢失?。?br>”;?>第四篇:mysql問題解決總結(jié)
第五篇:mysql數(shù)據(jù)庫要點(diǎn)總結(jié)