SQL中inner join、outer join和cross join的区别

Posted by Alex on April 24, 2019

SQL JOINS

总览

sql join

1. INNER JOIN

inner join

最常见的表关联,也是默认的JOIN方式,取A、B表的交集。

This is the simplest, most understood Join and is the most common. This query will return all of the records in the left table (table A) that have a matching record in the right table (table B).

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

2. LEFT JOIN

left join

返回表A的完全集,而B表中匹配的则有值,没有匹配的则以null值取代。

This query will return all of the records in the left table (table A) regardless if any of those records have a match in the right table (table B). It will also return any matching records from the right table.

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

3. RIGHT JOIN

right join

返回表B的完全集,而A表中匹配的则有值,没有匹配的则以null值取代。

This query will return all of the records in the right table (table B) regardless if any of those records have a match in the left table (table A). It will also return any matching records from the left table.

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

4. OUTER JOIN

又名 FULL OUTER JOIN or FULL JOIN

MySQL 中没有 FULL OUTER JOIN ,可以通过 UNION 实现类似功能

full outer join

返回A和B的并集。对于没有匹配的记录,则会以null做为值。

This query will return all of the records from both tables, joining records from the left table (table A) that match records from the right table (table B).

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

5.LEFT JOIN EXCLUDING INNER JOIN

left join excluding inner join

This query will return all of the records in the left table (table A) that do not match any records in the right table (table B).

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

right join excluding inner join

This query will return all of the records in the right table (table B) that do not match any records in the left table (table A).

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

outer join excluding inner join

This query will return all of the records in the left table (table A) and all of the records in the right table (table B) that do not match. I have yet to have a need for using this type of Join, but all of the others, I use quite frequently.

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

8. Cross Join

cross join

CROSS JOIN 把表A和表B的数据进行一个N*M的组合,即笛卡尔积。顾名思义,实际业务中切记别忘了数据过滤,慎用!

举个栗子.

总结

话不多说,看图:

sql join

前四个的Join 的思想不仅仅局限于SQL,也可以发散到数据处理上,思维不要僵化,哈哈。

同时 Oracle、MySQL、SQL Server 有些细微使用上的区别,就不在这儿记录啦。

Reference

Visual Representation of SQL Joins

CSDN Blog