這裡以可讀的方式使用表格對 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中文網其他相關文章!