mysql-數據(記錄)相關操做(增刪改查)及權限管理

1、介紹

在MySQL管理軟件中,能夠經過SQL語句中的DML語言來實現數據的操做,包括mysql

  1. 使用INSERT實現數據的插入
  2. UPDATE實現數據的更新
  3. 使用DELETE實現數據的刪除
  4. 使用SELECT查詢數據以及。

2、插入數據

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 …;

3、更新數據

語法:
    UPDATE 表名 SET
        字段1=值1,
        字段2=值2,
        WHERE CONDITION;

4、刪除數據

語法:
    DELETE FROM 表名 
        WHERE CONITION;

5、查詢數據

單表查詢語法:
    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
    員工id      id                  int             
    姓名        emp_name            varchar
    性別        sex                 enum
    年齡        age                 int
    入職日期     hire_date           date
    崗位        post                varchar
    職位描述     post_comment        varchar
    薪水        salary              double
    辦公室       office              int
    部門編號     depart_id           int



#建立表
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 sql

#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中不能使用聚合函數windows

「Having」是一個過濾聲明,是在查詢返回結果集之後對查詢結果進行的過濾操做,在Having中可使用聚合函數。ide

執行優先級從高到低:where > group by > having函數

 

注:用having就必定要用group by, 用group by不必定要有having。只要條件裏面的字段, 不是表裏面原先有的字段就須要用having。post

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.交叉鏈接(笛卡爾積):

交叉鏈接返回左表中的全部行,左表中的每一行與右表中的全部行組合,結果集的行數是兩個表的行數的乘積。(效率最低)ui

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:子查詢中能夠包含:INNOT INANYALLEXISTSNOT 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)

6、權限管理

#受權表
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 這個用戶能夠將他有的權限授予別的帳戶
相關文章
相關標籤/搜索