資料庫部分(MySql)_2
分組查詢
分組查詢通常和聚合函式結合使用,查詢條件中每個XXX就以XXX為分組的條件;
格式:每個A的平均B
select avg(B) from 表名 group by A;
having
在where後面只能寫普通欄位的條件;在having後面寫聚合函式的條件;having寫在group by的後面,where寫在最前面;
案例: 查詢每個部門的平均工資,只查詢平均工資大於2000的。
select deptno,avg(sal) a from emp group by deptno having a>2000;
SQL中各個關鍵字的順序
select
子查詢
巢狀在SQL語句中的查詢SQL語句稱之為子查詢;子查詢可以由多層巢狀;子查詢可寫在where和having後面作為查詢條件的值;
寫在建立表的時候 create table NEW表名 as (select X,Y from 表名);
寫在from後面當成一張新表使用(必須有別名)
select X,Y from (select * from EMP) T;
子查詢格式: select 欄位名,欄位名 from 表名1 欄位名=(select avg(欄位名) from 表名2);
1 案例:查詢部門平均工資最高的部門資訊
2 1)得到平均最高工資
3 select avg(工資) from EMP group by 部門編號 order by avg(工資) desc limit 0,1;
4 2)得到部門資訊
5 select 部門編號 from EMP group by 部門編號 having avg(工資)=(select avg(工資) from EMP group by 部門編號 order by avg(工資) desc limit 0,1);
6 3)得到部門資訊
7 select * from dept where 部門編號 in (select 部門編號 from EMP group by 部門編號 having avg(工資)=(select avg(工資) from EMP group by 部門編號 order by avg(工資) desc limit 0,1));
關聯查詢
同時查詢多張表的資料稱為關聯查詢。
1 案例:
2 1)查詢每個員工的姓名和相對應的部門名稱
3 select e.ename,d.dname from emp e,dept d where e.deptno=d.deptno;
4 2)查詢每個商品的標題、商品單價和對應的分類名稱
5 select t1,title,t1.price,t2.name from t_item t1,t_item_category t2 where t1.category_id=t2.id;
6 3)查詢在new york工作的所有員工資訊
7 select e.* from emp e,dept d where e.deptno=d.deptno and d.loc='new york';
8 4)查詢所有的員工資訊和對應的部門地點
9 select e.*,d.loc from emp e,dept d where e.deptno=d.deptno;
10 5)查詢員工資訊、員工工資、對應的部門名稱,要求工資大於2000
11 select e.ename,e.sal,d.dname from emp e,dept d where e.deptno=d.deptno and e.sal>2000;
笛卡爾積
關聯查詢如果不寫關聯關係,則查詢結果為兩張表的乘積;笛卡爾積是一種錯誤的查詢結果,在工作中不能出現。
等值連線和內連線
這兩種連線方式都是關聯查詢的查詢方式,效率相同;
等值連線: select * from A,B where A.X=B.X and A.Y=XXX;
內連線: select * from A join B on A.X=B.X where A.Y=XXX;
外連線: select * from A left/right join B on A.X=B.X where A.Y=XXX;
左外連線:以join右側表為主表查詢其所有資料和右側表的交際資料;
右外連線:以jion右側表為朱彪查詢其所有和左側表的交集資料。
1 案例:查詢所有員工的名字對應的部門名 2 select e.ename,d.dname from emp e left join dept d on e.deptno=d.deptno;