这里以可读的方式使用表格对 LEFT JOIN 和 RIGHT JOIN 进行了清晰、结构化的解释:
LEFT JOIN 和 RIGHT JOIN 是 SQL OUTER JOIN 的类型。它们用于根据匹配条件从两个表中获取数据,同时还包括其中一个表中不匹配的行。
SELECT columns FROM table1 LEFT JOIN table2 ON table1.column = table2.column;
EmployeeID | Name | DepartmentID |
---|---|---|
1 | Alice | 101 |
2 | Bob | 102 |
3 | Charlie | NULL |
4 | Diana | 104 |
DepartmentID | DepartmentName |
---|---|
101 | HR |
102 | IT |
103 | Finance |
查询:
SELECT Employees.Name, Departments.DepartmentName FROM Employees LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
Name | DepartmentName |
---|---|
Alice | HR |
Bob | IT |
Charlie | NULL |
Diana | 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 |
NULL | Finance |
Feature | LEFT JOIN | RIGHT JOIN |
---|---|---|
Included Rows | All rows from the left table. | All rows from the right table. |
Unmatched Rows | NULL for unmatched right table. | NULL for unmatched left table. |
Primary Use | Ensure all rows from the left table appear. | Ensure all rows from the right table appear. |
RIGHT JOIN
:当您想要右表中的所有数据时使用,无论左表中是否匹配。
通过整齐地呈现表格并用示例解释关键概念,结构仍然易于理解且具有视觉吸引力。
以上是掌握 SQL 连接:LEFT JOIN 与 RIGHT JOIN 举例说明的详细内容。更多信息请关注PHP中文网其他相关文章!