sql left join
时间: 2023-08-30 19:09:13 浏览: 105
The SQL LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side, when there is no match.
The basic syntax for a LEFT JOIN is as follows:
```
SELECT column1, column2, ...
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
```
In this example, the columns selected from table1 and table2 are listed in the SELECT statement. The ON clause specifies the join condition, which specifies how the tables are related.
For example, consider the following tables:
**Customers**
| CustomerID | CustomerName | ContactName | Country |
|------------|--------------|-------------|---------|
| 1 | Alfreds | Maria | Germany |
| 2 | Ana Trujillo | Ana | Mexico |
| 3 | Antonio | Antonio | Mexico |
| 4 | Around the Horn | Thomas | UK |
| 5 | Berglunds | Christina | Sweden |
**Orders**
| OrderID | CustomerID | OrderDate |
|---------|------------|-----------|
| 1 | 3 | 2021-01-01 |
| 2 | 2 | 2021-01-02 |
| 3 | 3 | 2021-01-03 |
| 4 | 1 | 2021-01-04 |
| 5 | 2 | 2021-01-05 |
To get a list of all customers and their orders (if any), we can use the following SQL statement:
```
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;
```
This would return the following result:
```
| CustomerName | OrderID |
|-----------------|---------|
| Alfreds | 4 |
| Ana Trujillo | 2 |
| Ana Trujillo | 5 |
| Antonio | 1 |
| Antonio | 3 |
| Around the Horn | NULL |
| Berglunds | NULL |
```
Note that customers who have not placed an order yet appear in the result with NULL values for the OrderID column.
阅读全文