SQL 的各种 join 用法

时间:2024-06-24 09:37:44

作者丨C.L. Moffatt

http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

  I am going to discuss seven different ways you can return data from two relational tables. I will be excluding cross Joins and self referencing Joins. The seven Joins I will discuss are shown below:

  1. INNER JOIN
  2. LEFT JOIN
  3. RIGHT JOIN
  4. OUTER JOIN
  5. LEFT JOIN EXCLUDING INNER JOIN
  6. RIGHT JOIN EXCLUDING INNER JOIN
  7. OUTER JOIN EXCLUDING INNER JOIN

下图展示了 LEFT JOIN、RIGHT JOIN、INNER JOIN、OUTER JOIN 相关的 7 种用法。

SQL 的各种 join 用法

具体分解如下:

1.INNER JOIN(内连接)

SQL 的各种 join 用法

SELECT < select_list > FROM Table_A A INNER JOIN Table_B B ON A.Key = B.Key

2.LEFT JOIN(左连接)

SQL 的各种 join 用法

SELECT < select_list > FROM Table_A A LEFT JOIN Table_B B ON A.Key = B.Key

3.RIGHT JOIN(右连接)

SQL 的各种 join 用法

SELECT < select_list > FROM Table_A A RIGHT JOIN Table_B B ON A.Key = B.Key

4.OUTER JOIN(外连接)

SQL 的各种 join 用法

SELECT < select_list > FROM Table_A A FULL OUTER JOIN Table_B B ON A.Key = B.Key

5.LEFT JOIN EXCLUDING INNER JOIN(左连接-内连接)

SQL 的各种 join 用法

SELECT < select_list > FROM Table_A A LEFT JOIN Table_B B ON A.Key = B.Key WHERE B.Key IS NULL

6.RIGHT JOIN EXCLUDING INNER JOIN(右连接-内连接)

SQL 的各种 join 用法

SELECT < select_list >
FROM Table_A A
RIGHT JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL

7.OUTER JOIN EXCLUDING INNER JOIN(外连接-内连接)

SQL 的各种 join 用法

SELECT < select_list >
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL
OR B.Key IS NULL