mysql-資料(記錄)相關操作(增刪改查)及許可權管理
一、介紹
在SQL/">MySQL管理軟體中,可以通過SQL語句中的DML語言來實現資料的操作,包括
- 使用INSERT實現資料的插入
- UPDATE實現資料的更新
- 使用DELETE實現資料的刪除
- 使用SELECT查詢資料以及。
二、插入資料
1. 插入完整資料(順序插入) 語法一: INSERT INTO 表名(欄位1,欄位2,欄位3…欄位n) VALUES(值1,值2,值3…值n); 語法二: INSERT INTO 表名 VALUES (值1,值2,值3…值n); 2. 指定欄位插入資料 語法: INSERT INTO 表名(欄位1,欄位2,欄位3…) VALUES (值1,值2,值3…); 3. 插入多條記錄 語法: INSERT INTO 表名 VALUES (值1,值2,值3…值n), (值1,值2,值3…值n), (值1,值2,值3…值n); 4. 插入查詢結果 語法: INSERT INTO 表名(欄位1,欄位2,欄位3…欄位n) SELECT (欄位1,欄位2,欄位3…欄位n) FROM 表2 WHERE …;
三、更新資料
語法: UPDATE 表名 SET 欄位1=值1, 欄位2=值2, WHERE CONDITION;
四、刪除資料
語法: DELETE FROM 表名 WHERE CONITION;
五、查詢資料
單表查詢語法: SELECT 欄位1,欄位2... FROM 表名 WHERE 條件 GROUP BY field HAVING 篩選 ORDER BY field LIMIT 限制條數 多表查詢語法: SELECT 欄位列表 FROM 表1 INNER|LEFT|RIGHT JOIN 表2 ON 表1.欄位 = 表2.欄位;
select關鍵字的定義順序:
SELECT DISTINCT <select_list> FROM <left_table> <join_type> JOIN <right_table> ON <join_condition> WHERE <where_condition> GROUP BY <group_by_list> HAVING <having_condition> ORDER BY <order_by_condition> LIMIT <limit_number>
select關鍵字的執行順序:
(7)SELECT (8)DISTINCT <select_list> (1)FROM <left_table> (3)<join_type> JOIN <right_table> (2)ON <join_condition> (4)WHERE <where_condition> (5)GROUP BY <group_by_list> (6)HAVING <having_condition> (9)ORDER BY <order_by_condition> (10)LIMIT <limit_number>
(一)、單表查詢
company.employee 員工ididint 姓名emp_namevarchar 性別sexenum 年齡ageint 入職日期hire_datedate 崗位postvarchar 職位描述post_commentvarchar 薪水salarydouble 辦公室officeint 部門編號depart_idint #建立表 create table employee( id int not null unique auto_increment, name varchar(20) not null, sex enum('male','female') not null default 'male', #大部分是男的 age int(3) unsigned not null default 28, hire_date date not null, post varchar(50), post_comment varchar(100), salary double(15,2), office int, #一個部門一個屋子 depart_id int ); #插入記錄 #三個部門:教學,銷售,運營 insert into employee(name,sex,age,hire_date,post,salary,office,depart_id) values ('egon','male',18,'20170301','老男孩駐沙河辦事處外交大使',7300.33,401,1), #以下是教學部 ('alex','male',78,'20150302','teacher',1000000.31,401,1), ('wupeiqi','male',81,'20130305','teacher',8300,401,1), ('yuanhao','male',73,'20140701','teacher',3500,401,1), ('liwenzhou','male',28,'20121101','teacher',2100,401,1), ('jingliyang','female',18,'20110211','teacher',9000,401,1), ('jinxin','male',18,'19000301','teacher',30000,401,1), ('成龍','male',48,'20101111','teacher',10000,401,1), ('歪歪','female',48,'20150311','sale',3000.13,402,2),#以下是銷售部門 ('丫丫','female',38,'20101101','sale',2000.35,402,2), ('丁丁','female',18,'20110312','sale',1000.37,402,2), ('星星','female',18,'20160513','sale',3000.29,402,2), ('格格','female',28,'20170127','sale',4000.33,402,2), ('張野','male',28,'20160311','operation',10000.13,403,3), #以下是運營部門 ('程咬金','male',18,'19970312','operation',20000,403,3), ('程咬銀','female',18,'20130311','operation',19000,403,3), ('程咬銅','male',18,'20150411','operation',18000,403,3), ('程咬鐵','female',18,'20140512','operation',17000,403,3) ; #ps:如果在windows系統中,插入中文字元,select的結果為空白,可以將所有字元編碼統一設定成gbk 表資料
簡單查詢:
#簡單查詢 SELECT id,name,sex,age,hire_date,post,post_comment,salary,office,depart_id FROM employee; SELECT * FROM employee; SELECT name,salary FROM employee; #避免重複DISTINCT SELECT DISTINCT post FROM employee; #通過四則運算查詢 SELECT name, salary*12 FROM employee; SELECT name, salary*12 AS Annual_salary FROM employee; SELECT name, salary*12 Annual_salary FROM employee; #定義顯示格式 CONCAT() 函式用於連線字串 SELECT CONCAT('姓名: ',name,'年薪: ', salary*12)AS Annual_salary FROM employee; CONCAT_WS() 第一個引數為分隔符 SELECT CONCAT_WS(':',name,salary*12)AS Annual_salary FROM employee; 結合CASE語句: SELECT ( CASE WHEN NAME = 'egon' THEN NAME WHEN NAME = 'alex' THEN CONCAT(name,'_BIGSB') ELSE concat(NAME, 'SB') END ) as new_name FROM emp;
1.where約束:
where字句中可以使用:
1. 比較運算子:> < >= <= <> !=
2. between 80 and 100 值在10到20之間
3. in(10,20,30) 值是10或20或30
4. like 'abc%'
%表示任意多字元
_表示一個字元
5. 邏輯運算子:在多個條件直接可以使用邏輯運算子 not and or
#1:單條件查詢 SELECT name FROM employee WHERE post='sale'; #2:多條件查詢 SELECT name,salary FROM employee WHERE post='teacher' AND salary>10000; #3:關鍵字BETWEEN AND SELECT name,salary FROM employee WHERE salary BETWEEN 10000 AND 20000; SELECT name,salary FROM employee WHERE salary NOT BETWEEN 10000 AND 20000; #4:關鍵字IS NULL(判斷某個欄位是否為NULL不能用等號,需要用IS) SELECT name,post_comment FROM employee WHERE post_comment IS NULL; SELECT name,post_comment FROM employee WHERE post_comment IS NOT NULL; SELECT name,post_comment FROM employee WHERE post_comment=''; 注意''是空字串,不是null ps: 執行 update employee set post_comment='' where id=2; 再用上條檢視,就會有結果了 #5:關鍵字IN集合查詢 SELECT name,salary FROM employee WHERE salary=3000 OR salary=3500 OR salary=4000 OR salary=9000 ; SELECT name,salary FROM employee WHERE salary IN (3000,3500,4000,9000) ; SELECT name,salary FROM employee WHERE salary NOT IN (3000,3500,4000,9000) ; #6:關鍵字LIKE模糊查詢 萬用字元’%’ SELECT * FROM employee WHERE name LIKE 'eg%'; 萬用字元’_’ SELECT * FROM employee WHERE name LIKE 'al__';
2.正則表示式查詢:
SELECT * FROM employee WHERE name REGEXP 'on$'; 除了模糊查詢 還可以使用正則表示式查詢 小結:對字串匹配的方式 WHERE name = 'onclose'; WHERE name LIKE 'on%'; WHERE name REGEXP 'on$';
3.group by 分組:
#檢視MySQL 5.7預設的sql_mode如下: mysql> select @@global.sql_mode; ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION #!!!注意 ONLY_FULL_GROUP_BY的語義就是確定select target list中的所有列的值都是明確語義,簡單的說來,在ONLY_FULL_GROUP_BY模式下,target list中的值要麼是來自於聚集函式的結果,要麼是來自於group by list中的表示式的值。 #設定sql_mole如下操作(我們可以去掉ONLY_FULL_GROUP_BY模式): mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
語法:
單獨使用GROUP BY關鍵字分組 SELECT post FROM employee GROUP BY post; 注意:我們按照post欄位分組,那麼select查詢的欄位只能是post,想要獲取組內的其他相關資訊,需要藉助函式 GROUP BY關鍵字和GROUP_CONCAT()函式一起使用 SELECT post,GROUP_CONCAT(name) FROM employee GROUP BY post;#按照崗位分組,並檢視組內成員名 SELECT post,GROUP_CONCAT(name) as emp_members FROM employee GROUP BY post; GROUP BY與聚合函式一起使用 select post,count(id) as count from employee group by post;#按照崗位分組,並檢視每個組有多少人
#如果沒有設定ONLY_FULL_GROUP_BY,也可以有結果,預設都是組內的第一條記錄,但其實這是沒有意義的 mysql> set global sql_mode='ONLY_FULL_GROUP_BY'; Query OK, 0 rows affected (0.00 sec) mysql> quit #設定成功後,一定要退出,然後重新登入方可生效 Bye mysql> use db1; Database changed mysql> select * from emp group by post; #報錯 ERROR 1055 (42000): 'db1.emp.id' isn't in GROUP BY mysql> select post,count(id) from emp group by post; #只能檢視分組依據和使用聚合函式
4.聚合函式:
#強調:聚合函式聚合的是組的內容,若是沒有分組,則預設一組 示例: SELECT COUNT(*) FROM employee; SELECT COUNT(*) FROM employee WHERE depart_id=1; SELECT MAX(salary) FROM employee; SELECT MIN(salary) FROM employee; SELECT AVG(salary) FROM employee; SELECT SUM(salary) FROM employee; SELECT SUM(salary) FROM employee WHERE depart_id=3;
5.having過濾:
“Where” 是一個約束宣告,使用Where來約束來自資料庫的資料,Where是在結果返回之前起作用的,且Where中不能使用聚合函式 。
“Having”是一個過濾宣告,是在查詢返回結果集以後對查詢結果進行的過濾操作,在Having中可以使用聚合函式。
執行優先順序從高到低:where > group by > having
注:用having就一定要用group by, 用group by不一定要有having。只要條件裡面的欄位, 不是表裡面原先有的欄位就需要用having。
6.order by 排序:
按單列排序 SELECT * FROM employee ORDER BY salary;#預設ASC升序 SELECT * FROM employee ORDER BY salary ASC; SELECT * FROM employee ORDER BY salary DESC;#降序 按多列排序:先按照age排序,如果年紀相同,則按照薪資排序 SELECT * from employee ORDER BY age, salary DESC;
7.limit 限制查詢記錄數:
示例: SELECT * FROM employee ORDER BY salary DESC LIMIT 3;#預設初始位置為0 ,查詢3條資料 SELECT * FROM employee ORDER BY salary DESC LIMIT 0,5; #從第0開始,即先查詢出第一條,然後包含這一條在內往後查5條 SELECT * FROM employee ORDER BY salary DESC LIMIT 5,5; #從第5開始,即先查詢出第6條,然後包含這一條在內往後查5條
(二)、多表查詢
SELECT 欄位列表 FROM 表1 INNER|LEFT|RIGHT JOIN 表2 ON 表1.欄位 = 表2.欄位;
1.交叉連線(笛卡爾積):
交叉連線返回左表中的所有行,左表中的每一行與右表中的所有行組合,結果集的行數是兩個表的行數的乘積。(效率最低)
mysql> select * from employee,department; +----+------------+--------+------+--------+------+--------------+ | id | name| sex| age| dep_id | id| name| +----+------------+--------+------+--------+------+--------------+ |1 | A| male|18 |200 |200 | 技術| |1 | A| male|18 |200 |201 | 人力資源| |1 | A| male|18 |200 |202 | 銷售| |1 | A| male|18 |200 |203 | 運營| |2 | B| female |48 |201 |200 | 技術| |2 | B| female |48 |201 |201 | 人力資源| |2 | B| female |48 |201 |202 | 銷售| |2 | B| female |48 |201 |203 | 運營| |3 | C| male|38 |201 |200 | 技術| |3 | C| male|38 |201 |201 | 人力資源| |3 | C| male|38 |201 |202 | 銷售| |3 | C| male|38 |201 |203 | 運營| +----+------------+--------+------+--------+------+--------------+
2.內連線:只連線匹配的行
INNER JOIN(內連線),也成為自然連線,找兩張表共有的部分,相當於利用條件從笛卡爾積結果中篩選出了正確的結果,內連線是從結果中刪除其他被連線表中沒有匹配行的所有行,所以內連線可能會丟失資訊。
mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee inner join department on employee.dep_id=department.id; +----+-----------+------+--------+--------------+ | id | name| age| sex| name| +----+-----------+------+--------+--------------+ |1 | A|18 | male| 技術| |2 | B|48 | female | 人力資源| |3 | C|38 | male| 人力資源| +----+-----------+------+--------+--------------+ #上述sql等同於 mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee,department where employee.dep_id=department.id;
3.外連線之左連線:
返回左表中的所有行,如果左表中行在右表中沒有匹配行,則結果中右表中的列返回空值。
select employee.id,employee.name,department.name as depart_name from employee left join department on employee.dep_id=department.id;
4.外連線之右連線:
與左連線正好相反,返回右表中的所有行,如果右表中行在左表中沒有匹配行,則結果中左表中的列返回空值。
select employee.id,employee.name,department.name as depart_name from employee right join department on employee.dep_id=department.id;
5.全外連線:顯示左右兩個表全部記錄
在內連線的基礎上增加左邊有右邊沒有的,右邊有左邊沒有的。是左外連線和右外連線的並集。
注:mysql不支援全外連線full join 但是可以用下面的方式實現( union與union all的區別:union會去掉相同的紀錄 )
select * from employee left join department on employee.dep_id = department.id union select * from employee right join department on employee.dep_id = department.id ;
(三)、子查詢
#1:子查詢是將一個查詢語句巢狀在另一個查詢語句中。 #2:內層查詢語句的查詢結果,可以為外層查詢語句提供查詢條件。 #3:子查詢中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等關鍵字 #4:還可以包含比較運算子:= 、 !=、> 、<等
1.帶in關鍵字的子查詢
#查詢平均年齡在25歲以上的部門名 select id,name from department where id in (select dep_id from employee group by dep_id having avg(age) > 25); #檢視技術部員工姓名 select name from employee where dep_id in (select id from department where name='技術'); #檢視不足1人的部門名(子查詢得到的是有人的部門id) select name from department where id not in (select distinct dep_id from employee);
2.帶比較運算子的子查詢
#查詢大於部門內平均年齡的員工名、年齡 select t1.name,t1.age from emp t1 inner join (select dep_id,avg(age) avg_age from emp group by dep_id) t2 on t1.dep_id = t2.dep_id where t1.age > t2.avg_age;
3.帶exists關鍵字的子查詢
#department表中存在dept_id=203,Ture mysql> select * from employee ->where exists ->(select id from department where id=200); #department表中存在dept_id=205,False mysql> select * from employee ->where exists ->(select id from department where id=204); Empty set (0.00 sec)
六、許可權管理
#授權表 user #該表放行的許可權,針對:所有資料,所有庫下所有表,以及表下的所有欄位 db #該表放行的許可權,針對:某一資料庫,該資料庫下的所有表,以及表下的所有欄位 tables_priv #該表放行的許可權。針對:某一張表,以及該表下的所有欄位 columns_priv #該表放行的許可權,針對:某一個欄位 #檢視自己的許可權 show grants; #建立使用者 create user使用者名稱@"主機地址" identified by "密碼"; create user 'A'@'1127.0.0.1' identified by '123'; create user 'B'@'192.168.1.%' identified by '123';#指定ip create user 'C'@'%' identified by '123';#任意使用者 #授權:對資料夾,對檔案,對檔案某一欄位的許可權 檢視幫助:help grant 常用許可權有:select,update,alter,delete all可以代表除了grant之外的所有許可權 語法: grant [許可權的名稱 select insert.... | all ] on 資料庫.表名to 使用者名稱@主機地址; 特點: 如果授權時,使用者不存在則直接自動建立使用者 #針對所有庫的授權:*.* grant select on *.* to 'A'@'localhost' identified by '123'; #只在user表中可以查到A使用者的select許可權被設定為Y 沒有 Grant_priv(授權)的許可權 #針對某一資料庫:db1.* grant select on db1.* to 'B'@'%' identified by '123'; #只在db表中可以查到B使用者的select許可權被設定為Y #針對某一個表:db1.t1 grant select on db1.t1 to 'C'@'%' identified by '123';#只在tables_priv表中可以查到C使用者的select許可權 #針對某一個欄位: grant select (id,name),update (age) on db1.t3 to 'D'@'localhost' identified by '123'; #可以在tables_priv和columns_priv中看到相應的許可權 #刪除許可權 revoke 許可權的名稱 on 資料庫.表名from 使用者名稱@"主機名" ; revoke select on db1.* from 'A'@'%'; #刪除使用者 drop user 使用者名稱@"主機地址";
注:新增許可權之後,要記得重新整理許可權
flush privileges;
如果要讓使用者擁有所有許可權,可以執行下面的命令:
grant [許可權的名稱 select insert.... | all ] on 資料庫.表名to 使用者名稱@主機地址 with grant option; with grant option 這個使用者可以將他有的許可權授予別的賬戶