Sql連表查詢
阿新 • • 發佈:2018-06-28
teacher rom SQ 學生 全外連接 連接 教師表 tom 重點 1.Union:使用union是組合兩張表,消去表中重復行,兩張表查詢的結果有相同數量的列、列類型相似;UNION ALL,不消除重復行
教師表:
重點:至少有一方保留全集,沒有匹配行用NULL代替
1)LEFT OUTER JOIN:結果集保留左表的所有行,但只包含第二個表與第一表匹配的行。第二個表相應的空行被放入NULL值
SELECT Students.ID,Students.Name,Majors.Name AS MajorName
FROM Students LEFT JOIN Majors
ON Students.MajorID = Majors.ID
結果:
SELECT Students.ID,Students.Name,Majors.Name AS MajorName
FROM Students RIGHT JOIN Majors
ON Students.MajorID = Majors.ID
結果:
教師表:
ID | Name |
---|---|
101 | Mrs Lee |
102 | Lucy |
學生表:
ID | Name | Age | City | MajorID |
---|---|---|---|---|
101 | Tom | 20 | BeiJing | 10 |
102 | Lucy | 18 | ShangHai | 11 |
SELECT Name FROM Students
UNION ALL
SELECT Name FROM Teachers
結果是:
ID | Name |
---|---|
101 | Tom |
102 | Lucy |
101 | Mrs Lee |
102 | Lucy |
2.INNER JOIN(內連接):內連接,只查匹配行
Majors表:
ID | Name |
---|---|
10 | English |
12 | Computer |
實例:查詢學生信息,包括ID,姓名、專業名稱
SELECT Students.ID,Students.Name,Majors.Name AS MajorName
FROM Students INNER JOIN Majors
ON Students.MajorID = Majors.ID
查詢結果:
ID | Name | MajorName |
---|---|---|
101 | Tom | English |
3.外連接 :左外連接、右外連接和全外連接,對應LEFT/RIGHT/FULL OUTER JOIN
重點:至少有一方保留全集,沒有匹配行用NULL代替
1)LEFT OUTER JOIN:結果集保留左表的所有行,但只包含第二個表與第一表匹配的行。第二個表相應的空行被放入NULL值
SELECT Students.ID,Students.Name,Majors.Name AS MajorName
FROM Students LEFT JOIN Majors
ON Students.MajorID = Majors.ID
結果:
ID | Name | MajorName |
---|---|---|
101 | Tom | English |
102 | Lucy | NULL |
2)RIGHT OUTER JOIN:右外連接保留了第二個表的所有行,但只包含第一個表與第二個表匹配的行。第一個表相應空行被入NULL值
SELECT Students.ID,Students.Name,Majors.Name AS MajorName
FROM Students RIGHT JOIN Majors
ON Students.MajorID = Majors.ID
結果:
ID | Name | MajorName |
---|---|---|
101 | Tom | English |
Null | NULL | Computer |
3)FULL OUTER JOIN:把兩個表所有的行都顯示在結果表中
SELECT Students.ID,Students.Name,Majors.Name AS MajorName
FROM Students FULL JOIN Majors
ON Students.MajorID = Majors.ID
結果:
ID | Name | MajorName |
---|---|---|
101 | Tom | English |
102 | Lucy | NULL |
NULL | NULL | Computer |
Sql連表查詢