在 SQL 中,INNER JOIN 和 OUTER JOIN 用于根据相关列组合两个或多个表中的行。主要区别在于这些连接如何处理不匹配的行。
INNER JOIN 仅返回两个表中具有匹配值的行。如果没有匹配,则该行将从结果中排除。
SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column;
EmployeeID | Name | DepartmentID |
---|---|---|
1 | Alice | 101 |
2 | Bob | 102 |
3 | Charlie | 103 |
DepartmentID | DepartmentName |
---|---|
101 | HR |
102 | IT |
查询:
SELECT employees.Name, departments.DepartmentName FROM employees INNER JOIN departments ON employees.DepartmentID = departments.DepartmentID;
Name | DepartmentName |
---|---|
Alice | HR |
Bob | IT |
OUTER JOIN 包含一个或两个表中的行,即使没有匹配项也是如此。 OUTER JOIN 共有三种类型:
返回左表中的所有行,即使右表中没有匹配项。
语法:
SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column;
查询:
SELECT employees.Name, departments.DepartmentName FROM employees INNER JOIN departments ON employees.DepartmentID = departments.DepartmentID;
Name | DepartmentName |
---|---|
Alice | HR |
Bob | IT |
Charlie | NULL |
返回右表中的所有行,即使左表中没有匹配项。
语法:
SELECT columns FROM table1 LEFT JOIN table2 ON table1.column = table2.column;
查询:
SELECT employees.Name, departments.DepartmentName FROM employees LEFT JOIN departments ON employees.DepartmentID = departments.DepartmentID;
Name | DepartmentName |
---|---|
Alice | HR |
Bob | IT |
NULL | Finance |
返回两个表中的所有行。没有匹配的行将填充 NULL。
语法:
SELECT columns FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;
查询:
SELECT employees.Name, departments.DepartmentName FROM employees RIGHT JOIN departments ON employees.DepartmentID = departments.DepartmentID;
Name | DepartmentName |
---|---|
Alice | HR |
Bob | IT |
Charlie | NULL |
NULL | Finance |
Feature | INNER JOIN | OUTER JOIN |
---|---|---|
Matching Rows | Returns only matching rows. | Returns all rows from one or both tables. |
Unmatched Rows | Excluded from the result. | Included with NULL values for missing columns. |
Performance | Generally faster. | Can be slower due to more data being processed. |
Variants | Single type. | Includes LEFT, RIGHT, and FULL OUTER JOIN. |
用例
INNER JOIN
:当您只需要匹配记录时使用,例如查找在特定部门工作的员工。LEFT JOIN
:当您需要一张表中的所有记录时使用,例如列出有或没有部门分配的所有员工。RIGHT JOIN
:当您需要第二个表中的所有记录时使用,例如列出有或没有分配员工的所有部门。
结论
以上是INNER JOIN 与 OUTER JOIN:深入了解 SQL 连接的详细内容。更多信息请关注PHP中文网其他相关文章!