mysql left join
时间: 2023-10-27 10:33:21 浏览: 97
SQL left join
The LEFT JOIN clause in MySQL is used to combine rows from two or more tables based on a related column between them. The resulting table will contain all the rows from the left table and matching rows from the right table. If there are no matching rows from the right table, then NULL values will be returned.
The syntax for a LEFT JOIN in MySQL is as follows:
SELECT column1, column2, ...
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
In this example, table1 is the left table and table2 is the right table. The ON clause specifies the column that is used to match the rows between the two tables.
For example, consider the following two tables:
Table1:
| id | name | age |
|----|-------|-----|
| 1 | John | 25 |
| 2 | Jane | 30 |
| 3 | David | 35 |
Table2:
| id | city |
|----|----------|
| 1 | New York |
| 2 | London |
| 4 | Paris |
To combine these two tables using a LEFT JOIN on the id column, the following query can be used:
SELECT Table1.name, Table2.city
FROM Table1
LEFT JOIN Table2
ON Table1.id = Table2.id;
The resulting table will be:
| name | city |
|-------|----------|
| John | New York |
| Jane | London |
| David | NULL |
Notice that the row with id=3 from Table1 does not have a corresponding row in Table2, so the city value is NULL in the resulting table.
阅读全文