1.Union:使用union是组合两张表,消去表中重复行,两张表查询的结果有相同数量的列、列类型相似;UNION ALL,不消除重复行
教师表:
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 |
原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/186655.html