sql三表查询_SQL第五关:多表查询
學習內容:
表的加法
學校數據庫里的課程表(course),新建課程表(course 1),數據結果一樣,新建數據內容不一樣。
2. 保留重復行
select 課程號,課程名稱 from course union all -- 保留重復行 select 課程號,課程名稱 from course1;表的聯結
關系數據庫由多張表組成,course,score,student,teacher為存放在school data base里的四張表。
2.
表中的每一行都與另一張表中的每一行合并,結果為兩張表之中的行的乘積。
實際工作中用的較少,沒有實際價值,但是其他所有聯結是在交叉聯結的基礎上加了相應的約束條件。
2.內聯結(inner join)
同時存在于兩張表中的數據。inner join
取出符合條件的行 交叉聯結select a.學號, a.姓名,b.課程號 --列名前加表名 from student as a inner join score as b -- a,b 簡化表名 on a.學號=b.學號 -- on 匹配條件3.左聯結
左側表中的所有數據全部取出來。
select a.學號, a.姓名,b.課程號 from student as a left join score as b on a.學號=b.學號select a.學號, a.姓名,b.課程號 from student as a left join score as b on a.學號=b.學號 where b.學號is Null; -- 只取存在于左表的數據3.右聯結(right join)
右側表中的所有數據全部取出來。
select a.學號, a.姓名,b.課程號 from student as a right join score as b on a.學號=b.學號select a.學號, a.姓名,b.課程號 from student as a right join score as b on a.學號=b.學號 where b.課程號 is Null; -- 只取存在于右表的數據4.全聯結(full join)
返回左表與右表中的所有行,若有匹配的行則進行合并,若沒有匹配的行,列顯示null值。
mysql不支持全聯結。
conclusion
生成固定行數的表單或者指明了要特定表里的所有數據,會使用左鏈接或者右鏈接。其他情況下一般使用內鏈接來獲取兩個表的公關部分。
多個表鏈接時是在from語句中加入,不會影響之前學習的sql查詢順序。
聯結應用案例
Q1: 查詢所有學生的學號、姓名、選課數、總成績
select a.學號, a.姓名,count(b.課程號) as 選課數,sum(b.成績) as 總成績 from student as a left join score as b -- 查詢所有學生所有需要左鏈接 on a.學號=b.學號 group by a.學號; -- 左鏈接需要用左邊的列來分組Q2 查詢平均成績大于85的所有學生的學號、姓名和平均成績
select a.學號, a.姓名,avg(b.成績) as 平均成績 from student as a left join score as b -- 查詢所有學生所有需要左鏈接 on a.學號=b.學號 group by a.學號 having avg(b.成績)>85;Q3 查詢學生的選課情況:學號,姓名,課程號,課程名稱 (三表聯結)
select a.學號,a.姓名,b.課程號,c.課程名稱 from student as a inner join score as b on a.學號=b.學號 inner join course as c on b.課程號=c.課程號;Case 表達式
case when<判斷表達式> then <表達式>when<判斷表達式> then <表達式>when<判斷表達式> then <表達式> ...else<表達式> end在查詢結果中顯示成績是及格還是不及格
select 學號, 課程號, 成績, (case when 成績>= 60 then'及格'when 成績< 60 then '不及格'else nullend) as 是否及格 from score;case 每次運行只返回一個結果
查詢出每門課程的及格人數和不及格人數
select 課程號, sum(case when 成績 >= 60 then 1 -- 應用函數 case 與 sum else 0 end) as 及格人數, sum(case when 成績 < 60 then 1 else 0 end) as 不及格人數case 表達式 注意事項
case表達式作用:
當有多種條件需要判斷時,可以使用case表達式。
使用分段[100-85],[85-70],[70-60],[<60]來統計各科成績,分別統計各分段人數,課程號和課程名稱
select a.課程號, b.課程名稱, sum(case when 成績 between 100 and 86 then 1 else 0 end) as '[100.85)', --加引號為字符串 sum(case when 成績 between 85 and 71 then 1 else 0 end) as '[85.70)', sum(case when 成績 between 70 and 60 then 1 else 0 end) as '[70.60]', sum(case when 成績 < 60 then 1 else 0 end) as 不及格人數 from score as a right join course as b --需查詢所有課程 右聯結 on a.課程號=b.課程號 group by a.課程號 , b.課程名稱; -- 多個列分組時,這幾個列的值全部相同才算一組 /* 為了顯示課程名稱,group by 里顯示課程名稱,而且group by里加入課程名稱需要和group by里的返回結果一致 */sqlzoo
Join '2012年歐洲足球錦標賽'
總結:
多表聯結時,group by 條件一定要小心分清
新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的sql三表查询_SQL第五关:多表查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 物质中的哲理
- 下一篇: linux编译lnx文件命令_Linux