1. 程式人生 > 實用技巧 >MySQL 之 進階操作

MySQL 之 進階操作

1、資料操作

(1)insert 增加資料

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

(2)delete 刪除資料

語法:
    DELETE FROM 表名  WHERE CONITION;

示例:
    DELETE FROM mysql.user 
        WHERE password=’’;

(3)update 修改資料

語法:
    UPDATE 表名 SET 欄位1=值1, 欄位2=值2  WHERE CONDITION;

示例:
    UPDATE mysql.user SET password=password(‘123’) 
        where user=’root’ and host=’localhost’;

(4)select 查詢資料

<1> 單表查詢

<2> 聯表查詢

語法
SELECT DISTINCT FROM 表名;

2、單表查詢

單表查詢的語法
SELECT DISTINCT 欄位1,欄位2... FROM 表名
                              WHERE 條件
                              GROUP BY field
                              HAVING 篩選
                              ORDER BY field
                              LIMIT 限制條數;
                    
單表查詢的關鍵字執行的優先順序
    from
    where
    group by
    select
    distinct
    having
    order by
    limit
    
單表查詢的執行過程
    1.找到表:from
    2.拿著where指定的約束條件,去檔案/表中取出一條條記錄
    3.將取出的一條條記錄進行分組group by,如果沒有group by,則整體作為一組
    4.執行select(也可以distinct去重)
    5.將分組的結果進行having過濾
    6.將結果按條件排序:order by
    7.限制結果的顯示條數

(1)前期建資料庫和表

# 建表和資料準備
  # 建立表
create table employee(
id int not null unique auto_increment,
emp_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(emp_name,sex,age,hire_date,post,salary,office,depart_id) values
#以下是教學部
('cai','male',78,'20150302','teacher',1000000.31,401,1),
('liu','male',81,'20130305','teacher',8300,401,1),
('ling','male',73,'20140701','teacher',3500,401,1),
('yongliang','male',28,'20121101','teacher',2100,401,1),
('marry','female',18,'20110211','teacher',9000,401,1),
('tom','male',18,'19000301','teacher',30000,401,1),
('liangliang','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)
;

(2)簡單查詢

# 查看錶中所有
select * from 表;   
# 指定列查詢
select emp_name,salary from employee;
# 在列中使用四則運算
select emp_name,salary*12 from employee;
# 重新命名
select emp_name,salary*12 as annul_salary from employee;
select emp_name,salary*12 annul_salary from employee;
# 去重 distinct
select distinct post from employee;
select distinct sex,post from employee;
# 定義顯示格式
 concat()函式     # 用於拼接字串
select concat('姓名 :',emp_name),concat('年薪:',salary*12) from employee;
 concat_ws()函式  第一個引數為分隔符
select concat_ws('|','a','b','c');
# 條件判斷
case when語句 == if條件判斷句
select
       (
           case
           when emp_name = 'cai' then
               emp_name
           when emp_name = 'liu' then
               CONCAT(emp_name,'_haha')
           else
               concat(emp_name, 'hehe')
           end
       ) as new_name
   from
       employee;

(3)根據條件篩選行 where

# 比較運算 = > < >= <= !=/<>
select * from employee where age>18;
select * from employee where salary<10000;
select * from employee where salary=20000;
# between 在一個範圍內;  between a and b    #[a,b]
select * from employee where salary between 10000 and 20000;
# in集合查詢 ; in(80,90,100) 值是80或90或100
select * from employee where salary in (17000,19000);
# like 模糊查詢
   # _ 萬用字元  表示一個字元長度的任意內容
select * from employee where emp_name like 'c__';
   # % 萬用字元  表示任意字元長度的任意內容
select * from employee where emp_name like 'c%';
select * from employee where emp_name like '%u';
select * from employee where emp_name like '%a%';
# regexp 正則匹配
select * from employee where emp_name regexp '^cai';

(4)邏輯運算 and or not

# and
	select * from employee where age>18 and post='teacher';
# or
	select * from employee where salary<10000 or salary>30000;
# not
	select * from employee where salary not in (10000,17000,18000);

(5)關於 null

# 關鍵字IS NULL(判斷某個欄位是否為NULL不能用等號,需要用IS)
  # 檢視崗位描述為NULL的員工資訊
select * from employee where post_comment is null;
  # 檢視崗位描述不為NULL的員工資訊
select * from employee where post_comment is not null;

(6)5個聚合函式

​ 強調:聚合函式聚合的是組的內容,若是沒有分組,則預設一組

count     # 統計次數
max		  # 求最大值
min		  # 求最小值
avg		  # 求平均值
sum 	  # 求和

(7)分組聚合 group by

​ 如果我們用unique的欄位作為分組的依據,則每一條記錄自成一組,這種分組沒有意義

​ 多條記錄之間的某個欄位值相同,該欄位通常用來作為分組的依據

# 單獨使用group by關鍵字分組
    select post from employee group by post;
    #注意:我們按照post欄位分組,那麼select查詢的欄位只能是post,想要獲取組內的其他相關資訊,需要藉助函式

#group by關鍵字和group_concat()函式一起使用
  #按照崗位分組,並檢視組內成員名
   select post,group_concat(emp_name) from employee group by post;
   select post,group_concat(emp_name) as emp_members from employee group by post;

# group by與聚合函式一起使用
   #按照崗位分組,並檢視每個組有多少人
    select post,count(id) as count from employee group by post;
   # 查詢各部門年齡在20歲以上的人的平均薪資
	select post,avg(salary) from employee where age>20 group by post;

(8)過濾 having (group by + 聚合函式)

# having與where不一樣的地方在於:
	執行優先順序從高到低:where > group by > having 
	1. Where 發生在分組group by之前,因而Where中可以有任意欄位,但是絕對不能使用聚合函式。
	2. having發生在分組group by之後,因而having中可以使用分組的欄位,無法直接取到其他欄位,可以使用聚合函式

# 查詢平均薪資大於1w的部門
select avg(salary) from employee group by post having avg(salary) > 10000;
# 查詢各崗位內包含的員工個數小於2的崗位名、崗位內包含員工名字、個數
select post,group_concat(emp_name),count(id) from employee group by post having count(id)<2;
# 查詢各崗位平均薪資大於10000的崗位名、平均工資
select post,avg(salary) from employee group by post having avg(salary) > 10000;
# 查詢各崗位平均薪資大於10000且小於20000的崗位名、平均工資
select post,avg(salary) from employee group by post having avg(salary) between 10000 and 20000;

(9)排序 order by

# 升序  asc (預設升序)
select * from employee order by salary;
select * from employee order by salary asc;
# 降序  desc 
select * from employee order by salary desc;

# 按多列排序:先按照age排序,如果年紀相同,則按照薪資排序
select * from employee order by age,salary;
select * from employee order by age,salary desc;
select * from employee order by age desc,salary;

(10)限制查詢的記錄數 limit

# 取前n條
select * from 表 order by 列 limit n; 
# 從m+1開始,取n條
select * from 表 order by 列 limit m,n; 
# 從m+1開始,取n條
select * from 表 order by 列 limit n offset m; 

小結: select * from 表 where 條件 group by 分組 having 過濾 order by 排序 limit n;

3、在命令提示符視窗中遇到的編碼問題解決方法:

1.臨時解決問題 在客戶端執行 set xxxx = utf8;
2.永久解決問題 在my.ini新增 set xxxx = utf8;
3.實時解決問題 create table 表名() charset=utf8;