--演示数据 IF OBJECT_ID('tempdb..#A') IS NOT NULL DROP TABLE #A GO CREATE TABLE #A ( A_ID INT, A_COL INT ) INSERT #A SELECT 1 , 1 UNION ALL SELECT 2 , NULL UNION ALL SELECT 3 , 1 UNION ALL SELECT 3 , 2 UNION ALL SELECT 4 , 1 IF OBJECT_ID('tempdb..#B') IS NOT NULL DROP TABLE #A GO CREATE TABLE #B( B_ID INT , B_COL INT ) INSERT INTO #B SELECT 1, 1 UNION ALL SELECT 2 , NULL UNION ALL SELECT NULL ,1 /* 1、 JOIN (INNER JOIN) INNER 可以省略 将一个表中的记录和另一个表中的记录的对应记录进行匹配,前提是两个表的相关列包含相同的值。 如果其中一个表的列值不同,或者根本没有值,查询将不会返回这些行。 既先对两表进行笛卡尔积 然后根据ON进行条件筛选 同FROM A,B WHERE A.ID = B.ID 即为等值连接 */ --INNER JOIN SELECT * FROM #A AS A INNER JOIN #B AS B ON A.A_ID = B.B_ID --下面两个查询结果是没有区别的 SELECT * FROM #A AS A INNER JOIN #B AS B ON A.A_ID = B.B_ID AND A.A_COL = 1 SELECT * FROM #A AS A INNER JOIN #B AS B ON A.A_ID = B.B_ID WHERE A.A_COL = 1 /* 2、 LEFT JOIN (LEFT OUTER JOIN ) 左向外联接的结果集包括LEFT OUTER子句中指定的左表的所有行,而不仅仅是联接列所匹配的行。 如果左表的某行在右表中没有匹配行,则在相关联的结果集中右表的所有选择列表均为空值 */ --LEFT JOIN SELECT * FROM #A AS A LEFT JOIN #B AS B ON A.A_ID = B.B_ID SELECT * FROM #A AS A LEFT JOIN #B AS B ON A.A_COL = 1 --即把1的进行CROSS JOIN 非1的加上 --以下两个语句的区别 SELECT * FROM #A AS A LEFT JOIN #B AS B ON A.A_COL = 1 WHERE B.B_COL = 1 SELECT * FROM #A AS A LEFT JOIN #B AS B ON A.A_COL = 1 AND B.B_COL = 1 /* 3、 RIGHT JOIN (RIGHT OUTER JOIN ) 右向外联接是左向外联接的反向联接。将返回右表的所有行。如果右表的某行在左表中没有匹配行,则将为左右返回空值。 */ --RIGHT JOIN SELECT * FROM #A AS A RIGHT JOIN #B AS B ON A.A_ID = B.B_ID SELECT * FROM #A AS A RIGHT JOIN #B AS B ON A.A_ID = B.B_ID AND A.A_COL = 1 SELECT * FROM #A AS A RIGHT JOIN #B AS B ON A.A_ID = B.B_ID AND A.A_COL = 1 WHERE B.B_COL <> 1 SELECT * FROM #A AS A RIGHT JOIN #B AS B ON A.A_COL = 1 /* 4、 完整外部联接(FULL JOIN 或者 FULL OUTER JOIN) 完整外部联接返回左右和右表中的所有行,当某行的在另一个表中没有匹配行时,则另一个表的选择列表包含空值。 如果表之间有匹配行,则整个结果集行包含基表的数据值。 对于完整外部联接,可以这样理解它的输出结果:先生成LEFT JOIN 的结果,将表B中所有未出现在结果中的行添加到结果集中, 对于添加到结果集中的第一行,应该出现表A列值的地方用NULL代替 */ SELECT * FROM #A AS A FULL JOIN #B AS B ON A.A_ID = B.B_ID SELECT * FROM #A AS A FULL JOIN #B AS B ON A.A_ID = 1 /* 5、交叉联接(CROSS JOIN ) 交叉联接返回左表中的所有行,左表中的第一行与右表中的所有行组合。交叉联接也称为笛卡尔积 */ --CROSS JOIN SELECT * FROM #A AS A CROSS JOIN #B AS B