联接分为:
left join(左联接): 返回包括左表中的所有记录和右表中联结字段相等的记录。3
right join(右联接): 返回包括右表中的所有记录和左表中联结字段相等的记录。4
inner join(等值连接): 只返回两个表中联结字段相等的行。
我们主要使用左联接。
例子:
1.在学院表、专业表中,查询开设4年制专业的所有学院及其下设专业, 不符合条件、未设专业的学院(部门)亦一并列出 SELECT D.Name AS Department ,M.Name AS Major FROM tb_Department AS D LEFT JOIN tb_Major AS M ON M.DepartmentNo=D.No WHERE |
M.Length=4; 例题中的错误是左联接中保留的外部行将被WHERE子句删除。 修改成: |
SELECT
D.Name AS Department
,M.Name AS Major
FROM
tb_Department AS D
LEFT JOIN tb_Major AS M ON M.DepartmentNo=D.No AND M.Length=4;
2.在学院(部门)表、专业表、班级表中,查询各学院(部门)下设的所有班级,若某学院(部门)无班级,亦一并列出
SELECT
D.Name AS Department
,RIGHT(CONVERT(VARCHAR,C.Year),2)+M.ShortName+ISNULL(C.AdministrationClass,‘‘) AS Class
FROM
tb_Department AS D
LEFT JOIN tb_Major AS M ON D.No=M.DepartmentNo
JOIN tb_Class AS C ON M.No=C.MajorNo;
例题中的错误是左联接能为左侧表保留不匹配的外部行,但外部行中对应右侧表的属性取值均为NULL,而这些NULL值在随后的内联接中永远找不到匹配,故这些外部行最终无法保留。
修改为:
SELECT
D.Name AS Department
,RIGHT(CONVERT(VARCHAR,C.Year),2)+M.ShortName+ISNULL(C.AdministrationClass,‘‘) AS Class
FROM
tb_Department AS D
LEFT JOIN
(tb_Major AS M
JOIN tb_Class AS C ON M.No=C.MajorNo) ON D.No=M.DepartmentNo;