1 minute read

  参考 Join (SQL),本文仅作总结。

  假设有两张表:

1. Cross Join

  即笛卡尔乘积 (Cartesian Product)。标准语法为:

SELECT *  
FROM   employee CROSS JOIN department;  

也可以隐式地写为:

SELECT *  
FROM   employee, department;

得到的表结构为 (LastName, DepartmentID, DepartmentID, DepartmentName)

2. Inner Join

  不标准地说,Inner Join 就是 Cross Join 加上了一个 where 子句,如:

SELECT *    
FROM   employee, department   
WHERE  employee.DepartmentID = department.DepartmentID;  

当然,这也是隐式的写法。标准语法为:

SELECT *  
FROM   employee INNER JOIN department   
ON     employee.DepartmentID = department.DepartmentID;  

2.1 Equi-Join

  是 Inner Join 的特殊形式,特指 where 子句中的条件为 Equality Comparison,如上面的例子。不过它也有自己独特的语法:

SELECT *  
FROM   employee INNER JOIN department   
USING  (DepartmentID)  

注意 using 子句会消除掉一个 DepartmentID 列,即得到 (LastName, DepartmentID, DepartmentName),而不是 (LastName, DepartmentID, DepartmentID, DepartmentName)。可以把 using 子句看做是特殊的 where 子句。

2.2 Natural Join

  是 Equi-Join 的特殊形式。Natural Join 不用指定 Equality Comparison 的 Column,它会自动查找做 Natural Join 的表中同名的 Column,隐式地在这个 Column 上使用 using 子句。它的标准语法为:

SELECT *  
FROM   employee NATURAL JOIN department;  

如果有多个同名 Column (或者 Equi-Join 中 USING(Column1, …, Column N)),则必须这多个 Column 都相等的列才被检入 Join 的结果中。

3. Outer Join

  Outer Join 的定义不太好描述,我们先来看看 Inner Join 的示意图:

由于 (John, NULL) 和 (35, Marketing) 在对面表中没有匹配的记录,所以它们不会出现在 Inner Join 的结果中,而 Outer Join 就可以让这些没有匹配的记录出现在结果中。

3.1 Left Outer Join

  指 “LEFT OUTER JOIN” 关键字左方的表中的记录都会出现在结果中,如:

SELECT *    
FROM   employee  LEFT OUTER JOIN department    
ON     employee.DepartmentID = department.DepartmentID;

得到的结果是:

示意图为:

3.2 Right Outer Join

  指 “RIGHT OUTER JOIN” 关键字右方的表中的记录都会出现在结果中,如:

SELECT *   
FROM   employee RIGHT OUTER JOIN department   
ON     employee.DepartmentID = department.DepartmentID;

得到的结果是:

示意图为:

3.3 Full Outer Join

  全外联结,即左外联结和右外联结的综合 (并集)。如:

SELECT *    
FROM   employee FULL OUTER JOIN department   
ON     employee.DepartmentID = department.DepartmentID;  

得到的结果是:

4. Self Join

  指表与自身的联结。

Categories:

Updated:

Comments