04 數據庫——數據庫表單查詢(where ,分組,聚合函數,篩選,去重,排序)、多表查詢、子查詢


前期表准備

create table emp(
  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 emp(name,sex,age,hire_date,post,salary,office,depart_id) values
('jason','male',18,'20170301','張江第一帥形象代言',7300.33,401,1), #以下是教學部
('egon','male',78,'20150302','teacher',1000000.31,401,1),
('kevin','male',81,'20130305','teacher',8300,401,1),
('tank','male',73,'20140701','teacher',3500,401,1),
('owen','male',28,'20121101','teacher',2100,401,1),
('jerry','female',18,'20110211','teacher',9000,401,1),
('nick','male',18,'19000301','teacher',30000,401,1),
('sean','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 * from emp\G;

當表字段特別多的時候 結果的排版可能會出現混亂的現象 你可以在查詢語句加\G來規范查詢結果

# 語法順序
select
from
where
group by
(having)

# 再識執行順序
from
where 
group by
(having)
select

#完整版sql語句的查詢
select distinct post,avg(salary)

from table1 where id > 1
group by post
having avg(salary) > 1000
order by avg(salary)
limit 5,5



 

二、where約束條件

# 1.查詢id大於等於3小於等於6的數據
select id,name from emp where id >= 3 and id <= 6;
select *  from emp where id between 3 and 6;  
# 2.查詢id小於3或者大於6的數據
select *  from emp where id not between 3 and 6;

# 3.查詢薪資是20000或者18000或者17000的數據
select * from emp where salary = 20000 or salary = 18000 or salary = 17000;
select * from emp where salary in (20000,18000,17000);  # 簡寫

# 4.查詢薪資不在20000,18000,17000范圍的數據
select * from emp where salary not in (20000,18000,17000);

# 5.查詢員工姓名中包含o字母的員工姓名和薪資
# 在你剛開始接觸mysql查詢的時候,建議你按照查詢的優先級順序拼寫出你的sql語句
"""
先是查哪張表 from emp
再是根據什么條件去查 where name like ‘%o%’
再是對查詢出來的數據篩選展示部分 select name,salary
"""
模糊匹配  like
    %:匹配多個任意字符 _:匹配一個任意字符
select name,salary from emp where name like '%o%';

# 6.查詢員工姓名是由四個字符組成的員工姓名與其薪資
select name,salary from emp where name like '____';
select name,salary from emp where char_length(name) = 4;

# 7.查詢崗位描述為空的員工名與崗位名  針對null不能用等號,只能用is
select name,post from emp where post_comment = NULL;  # 查詢為空!
select name,post from emp where post_comment is NULL;
select name,post from emp where post_comment is not NULL;

三、group by 分組

1.分組前戲 ——設置嚴格模式

# 1.按部門分組之分組前戲
select * from emp group by post;  
# 分組后取出的是每個組的第一條數據,也就是每個組從上到下取出第一個人的所有信息
select id,name,sex from emp group by post;  
# 驗證,發現還是上面那幾個人,只是信息少了,只顯示了id ,name,sex而已

1.分組之后應該做到最小單位是組,而不應該再展示組內的單個數據信息,那樣就沒分組的意義了,比如你以國家分組,直接看國家有哪些就好了,不必要看國家里面的某個人
2.MySQL中分組之后 只能拿到分組的字段信息 無法直接獲取其他字段信息,但是你可以通過其他方法(聚合函數)間接的獲取
3.上面兩個語句如果不報錯,取到了數據,那就說明沒有設置嚴格模式,需要去設置嚴格模式
#設置嚴格模式: show variables like '%mode%'; set session 當前窗口有效 set global 全局有效 set global sql_mode="strict_trans_tables,only_full_group_by"; # 設置完成后,重新鏈接客戶端,驗證一下: select * from emp group by post; # 報錯 select id,name,sex from emp group by post; # 報錯 select post from emp group by post; # 獲取部門信息 #查詢詳細信息報錯,只能查詢到分組的信息,說明設置成功 強調:只要分組了,就不能夠再“直接”查找到單個數據信息了,只能獲取到組名

2.聚合函數 max min avg sum count

以組為單位統計組內數據>>>聚合查詢(聚集到一起合成為一個結果)
如果一張表沒有寫group by默認所有的數據就是一組
#在分組后,即select后面或者having后面才能使用

# 每個部門的最高工資 select post,max(salary) from emp group by post; PS:給字段取別名(as也可以省略,但是一般不要這樣干) select post as 部門,max(salary) as 最高工資 from emp group by post; # 每個部門的最低工資 select post,min(salary) from emp group by post; # 每個部門的平均工資 select post,avg(salary) from emp group by post; # 每個部門的工資總和 select post,sum(salary) from emp group by post; # 每個部門的人數總數 select post,count(id) from emp group by post; 在統計分組內個數的時候,填寫任意非空字段都可以完成計數,推薦使用能夠非空且唯一標識數據的字段,比如id字段

# 聚合函數max min sum count avg只能在分組之后才能使用,也就是緊跟着select用或者緊跟着having(分組后的二次where)
select id,name,age from emp where max(salary) > 3000; # 報錯!
select max(salary) from emp;
# 正常運行,不分組意味着每一個人都是一組,等運行到max(salary)的時候已經經過where,group by操作了,只不過我們都沒有寫這些條件

 

3.group_concat 和 concat

group_concat(分組之后用)不僅可以用來顯示除分組外字段還有拼接字符串的作用

1.group_concat 顯示分組外字符   拼接字符串
#查詢分組之后的部門名稱和每個部門下所有人的姓名
select post,group_concat(name) from emp group by post;
#在每個人的名字前后拼接字符 select post,group_concat('D_',name,"_SB") from emp group by post;
#group_concat()能夠拿到分組后每一個數據指定字段(可以是多個)對應的值 select post,group_concat(name,": ",salary) from emp group by post; 2.concat拼接 as語法使用
不分組時用)就是用來拼接字符串達到更好的顯示效果
select name as 姓名,salary as 薪資 from emp;
select concat("NAME: ",name) as 姓名,concat("SAL: ",salary) as 薪資 from emp;

# 如果拼接的符號是統一的可以用 concat_ws
select concat_ws(':',name,age,sex) as info from emp;


小技巧: concat就是用來幫你拼接數據,不分組情況下使用 group_concat 分組之后使用,可以拼接數據也可以用來顯示其他字段信息 # 補充as語法 既可以給字段起別名也可以給表起
select emp.id,emp.name from emp as t1; # 報錯  因為表名已經被你改成了t1
select t1.id,t1.name from emp as t1;

3.查詢四則運算
# 查詢每個人的年薪
select name,salary*12 as annual_salary from emp;
select name,salary*12 annual_salary from emp;  # as可以省略

4.練習題

# 剛開始查詢表,一定要按照最基本的步驟,先確定是哪張表,再確定查這張表有沒有限制條件,再確定是否需要分類,最后再確定需要什么字段對應的信息

1. 查詢崗位名以及崗位包含的所有員工名字
2. 查詢崗位名以及各崗位內包含的員工個數
3. 查詢公司內男員工和女員工的個數
4. 查詢崗位名以及各崗位的平均薪資
5. 查詢崗位名以及各崗位的最高薪資
6. 查詢崗位名以及各崗位的最低薪資
7. 查詢男員工與男員工的平均薪資,女員工與女員工的平均薪資
"""
參考答案:
select post,group_concat(name) from emp group by post;
select post,count(id) from emp group by post;
select sex,count(id) from emp group by sex;
select post,avg(salary) from emp group by post;
select post,max(salary) from emp group by post;
select post,min(salary) from emp group by post;
select sex,avg(salary) from emp group by sex;
"""
8、統計各部門年齡在30歲以上的員工平均工資
select post,avg(salary) from emp where age > 30 group by post; 
# 對where過濾出來的虛擬表進行一個分組
View Code

四、having 篩選

跟where是一模一樣的 也是用來篩選數據 但是having是跟在group by之后的 where是對整體數據做一個初步的篩選 而having是對分組之后的數據再進行一次針對性的篩選

1、統計各部門年齡在30歲以上的員工平均工資,並且保留平均工資大於10000的部門 select post,avg(salary) from emp where age > 30 group by post where avg(salary) > 10000; # 報錯 select post,avg(salary) from emp where age >= 30 group by post having avg(salary) > 10000; 強調:having必須在group by后面使用 select * from emp having avg(salary) > 10000; # 報錯

五、distinct 去重

# 對有重復的展示數據進行去重操作

#去重一定要滿足數據是一模一樣的情況下 才能達到去重的效果
#如果你查詢出來的數據中包含主鍵字段,那么不可能去重成功

#只要有一個不一樣 都不能算是的重復的數
select distinct id,age from emp; #去重失敗,id不一樣,即使age一樣也沒毛用
select distinct post from emp; #成功

六、limit 限制條數

# 限制展示條數
select * from emp limit 5;  # 只展示數據的五條
# 分頁顯示
select * from emp limit 5,5; #第6條開始,往后展示5條 
    當limit只有一個參數的時候  表示的是只展示幾條
    當limit有兩個參數的時候   第一個參數表示的起始位置,是索引
    第二個參數表示從起始位置開始往后展示的條數
    
# 查詢工資最高的人的詳細信息
select * from emp order by salary desc limit 1;

七、regexp 正則

# 在編程中 只要看到reg開頭的 基本上都是跟正則相關
select * from emp where name regexp '^j.*(n|y)$';

re模塊中
findall:分組優先 會將括號內正則匹配到的優先返回
match:從頭開始匹配 匹配到一個就直接返回
res = match('^j.*n$','jason')
print(res.group())
search:整體匹配 匹配到一個就直接返回

八、order by 排序

select * from emp order by salary asc; #默認升序排
select * from emp order by salary desc; #降序排

select * from emp order by age desc; #降序排

#先按照age降序排,在年紀相同的情況下再按照薪資升序排
select * from emp order by age desc,salary asc; 

# 統計各部門年齡在10歲以上的員工平均工資,並且保留平均工資大於1000的部門,然后對平均工資進行排序
select post,avg(salary) from emp
    where age > 10
    group by post
    having avg(salary) > 1000
    order by avg(salary)
    ;

九、多表查詢

#建表
create table dep(
id int,
name varchar(20) 
);

create table emp(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') not null default 'male',
age int,
dep_id int
);

#插入數據
insert into dep values
(200,'技術'),
(201,'人力資源'),
(202,'銷售'),
(203,'運營');

insert into emp(name,sex,age,dep_id) values
('jason','male',18,200),
('egon','female',48,201),
('kevin','male',38,201),
('nick','female',28,202),
('owen','male',18,200),
('jerry','female',18,204)
;

# 當初為什么我們要分表,就是為了方便管理,在硬盤上確實是多張表,但是到了內存中我們應該把他們再拼成一張表進行查詢才合理
創建表

 

當初為什么我們要分表,就是為了方便管理,在硬盤上確實是多張表,但是到了內存中我們應該把他們再拼成一張表進行查詢才合理

#笛卡爾積

select * from emp,dep;  
# 左表一條記錄與右表所有記錄都對應一遍,即10*4=40條 >>>笛卡爾積
# 將所有的數據都對應了一遍,雖然不合理但是其中有合理的數據,現在我們需要做的就是找出合理的數據
# 查詢員工及所在部門的信息
select * from emp,dep where emp.dep_id = dep.id;
# 查詢部門為技術部的員工及部門信息
select * from emp,dep where emp.dep_id = dep.id and dep.name = '技術';

其實將兩張表關聯到一起的操作,有專門對應的方法:內連接、左連接、右鏈接、全連接

# 1、內連接:只鏈接兩張表有對應關系的記錄
select * from emp inner join dep on emp.dep_id = dep.id;
select * from emp inner join dep on emp.dep_id = dep.id
                            where dep.name = "技術";

# 2、左連接: 在內連接的基礎上保留左表沒有對應關系的記錄,沒有部門信息null補全
select * from emp left join dep on emp.dep_id = dep.id;

# 3、右連接: 在內連接的基礎上保留右表沒有對應關系的記錄,沒有員工信息null補全
select * from emp right join dep on emp.dep_id = dep.id;

# 4、全連接:在內連接的基礎上保留左、右面表沒有對應關系的的記錄,空白全用null補全
# 只要將左連接和右連接的sql語句中間加一個union連起來就變成全連接
select * from emp left join dep on emp.dep_id = dep.id
union
select * from emp right join dep on emp.dep_id = dep.id;

十、子查詢

就是將一個查詢語句的結果用括號括起來當作另外一個查詢語句的條件去用,括號里面語句末尾不能加分號

 

# 1.查詢部門是技術或者人力資源的員工信息
"""
先獲取技術部和人力資源部的id號,再去員工表里面根據前面的id篩選出符合要求的員工信息
"""
select * from emp where dep_id in (select id from dep where name = "技術" or name = "人力資源");

# 2.每個部門最新入職的員工 思路:先查每個部門最新入職的員工,再按部門對應上聯表查詢
# 可以給表起別名
# 可以給查詢出來的虛擬表起別名
# 可以給字段起別名
select t1.id,t1.name,t1.hire_date,t1.post,t2.* from emp as t1
inner join
(select post,max(hire_date) as max_date from emp group by post) as t2
on t1.post = t2.post
where t1.hire_date = t2.max_date;

我的方法:
#先選出每個部門的最新來的日期
select max(hire_date) from emp group by post;
#最新日期作為條件
select name,hire_date,post 
from emp where hire_date
in (select max(hire_date) from emp group by post) ;


# 查詢平均年輕在25歲以上的部門名
方法一:子查詢
select name from dep
where id in
(select dep_id from emp group by dep_id having avg(age)>25);
方法二:連表查詢
select dep.name from emp inner join dep on emp.dep_id = dep.id
group by dep.name
having avg(age) > 25;

"""
記住一個規律,表的查詢結果可以作為其他表的查詢條件,也可以通過其別名的方式把它作為一張虛擬表去跟其他表做關聯查詢
"""

select * from emp inner join dep on emp.dep_id = dep.id;

十一、exist(了解)

EXISTS關字鍵字表示存在。在使用EXISTS關鍵字時,內層查詢語句不返回查詢的記錄,
而是返回一個真假值,True或False。
當返回True時,外層查詢語句將進行查詢
當返回值為False時,外層查詢語句不進行查詢。
select * from emp
    where exists
    (select id from dep where id > 203);

MySQL中的注釋
-- #

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM