mysql关联分组查询,Mysql 分组查询/子查询/关联查询【总结】
1、分組查詢:group by
通常和聚合函數結合使用,以組為單位進行統計,一般情況下,題目中每個XX就在group by后面寫這個XX;
例:查詢每個部門的最高工資:
select deptno,max(sal) from emp group by deptno;
例:查詢每個分類下的商品最大價格:
select category_id,max(price) from t_item group by category_id;
例:查詢每個部門中工資大于1500的人數:
select deptno,sal from emp where sal > 1500 group by deptno;
例:查詢每個領導手下的人數:
select mgr,count(*) from emp where mgr is not null group by mgr;
如果需要使用多個字段進行分組,直接在group by后面寫多個字段名通過逗號分隔:
例:查詢按每個部門下每個領導的手下人數:
select deptno,mgr,count(*) from emp where mgr is not null group by deptno,mgr;
having:要寫在group by后面和它結合使用:
where:后面只能寫普通字段的條件不能寫聚合函數;
having:后面可以寫普通字段條件也可以寫聚合函數推薦在having后面只寫聚合函數;
例:查詢每個部門的平均工資,要求平均工資大于2000:
select deptno,avg(sal) a from emp group by deptno having a > 2000;
例:查詢每個分類的平均單價,過濾掉平均單價低于100的:
select category_id,avg(price) a from t_item group by category_id having a >= 100;
2、子查詢:
例:查詢emp表工資中最高的員工信息:
正常情況下需要查出最高工資的員工,然后再查出員工的信息:
select max(sal) from emp;(查詢結果為5000)
select * from emp where sal = 5000;
使用子查詢:
select * from emp where sal = (select max(sal) from emp);
例:查詢工資最低的員工的所在部門的同事信息:
首先查詢到工資最低的員工:
select min(sal) from emp;
通過最低工資找到所在部門編號:
select deptno from emp where sal = (select min(sal) from emp);
通過編號找到其他的員工信息:
select * from emp where deptno = (select deptno from emp where sal = (select min(sal) from emp));
擴展題:查詢平均工資最高的部門信息:
得到每個部門的平均工資:
select deptno,avg(sal) from emp group by deptno;
得到最高的平均工資:
select avg(sal) a from emp group by deptno order by a desc limit 0,1;
通過最高的平均工資得到部門編號:(這里為了嚴謹考慮有多個部門工資平均值相同且為最高平均工資的情況)
select deptno from emp group by deptno having avg(sal) = (select avg(sal) a from emp group by deptno order by a desc limit 0,1);
通過部門編號獲得部門信息:
select * from dept where deptno in(select deptno from emp group by deptno having avg(sal) = (select avg(sal) a from emp group by deptno order by a desc limit 0,1));
子查詢可以寫在什么位置:
寫在where或having后面,當做查詢條件的值;
寫在創建表的時候,把查詢結果保存成一張新的表;
寫在from的后面當成一張虛擬表,必須有別名。
3、關聯查詢:
同時查詢多張表的數據稱為關聯查詢(能查詢到的只能是兩張表的交集)。
例:查詢每一個員工的姓名和對應的部門名稱:
select e.ename,d.dname from emp e,dept d where e.deptno = d.deptno;
笛卡爾積:如果關聯查詢不寫關聯關系則結果為兩張表的乘積,這個乘積稱為笛卡爾積,笛卡爾積為一種錯誤的查詢結果,切記工作中不要出現。
關聯查詢的查詢方式:等值連接和內連接
等值連接:select * from A,B where A.x = B.x and A.age = 18;
內連接:select * from A [inner] join B on A.x = B.x where A.age = 18; [inner]可以省略不寫
等值連接和內連接查詢到的內容一樣,都為兩張表中有關聯關系的數據(交集部分)。
例:查詢每一個員工的姓名和對應部門名稱:(用內連接的方式)
select e.ename,d.deptno from emp e join dept d on e.deptno = d.deptno;
外連接:內連接和等值連接查詢到的是交集數據,外連接查詢到的是某一張表的全部數據 + 另一張表的交集數據。
左/右外連接:select * from A left/right join B on A.x = B.x where A.age = 18;(左外連接就是以左邊的表即A為主表和右邊表的交集)
關聯查詢總結:
關聯查詢的查詢方式:等值連接、內連接、外連接;
如果想查詢的數據為兩張表的交集數據使用等值連接和內連接(推薦);
如果查詢的數據是一張表的全部數據和領一張表的交集數據則使用外連接;
總結
以上是生活随笔為你收集整理的mysql关联分组查询,Mysql 分组查询/子查询/关联查询【总结】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql联合查询的几种方式
- 下一篇: mysql关联查询去重_mysql |