扫码一下
查看教程更方便
sql left join返回左表中的所有行,即使右表中没有匹配项。这意味着如果 on 子句匹配右表中的 0(零)条记录;连接仍将在结果中返回一行,但在右表的每一列中都为 null。
这也就是说 left join 返回左表中的所有记录,加上右表中匹配的值,或者在右表中没有匹配的情况下返回 null。
left join的基本语法如下。
select table1.column1, table2.column2...
from table1
left join table2
on table1.common_field = table2.common_field;
在这里,给定的条件可以是基于我们自己的要求的任何给定的表达式。
现在我们看如下的两张表
---- ---------- ----- ----------- ----------
| id | name | age | address | salary |
---- ---------- ----- ----------- ----------
| 1 | ramesh | 32 | ahmedabad | 2000.00 |
| 2 | khilan | 25 | delhi | 1500.00 |
| 3 | kaushik | 23 | kota | 2000.00 |
| 4 | chaitali | 25 | mumbai | 6500.00 |
| 5 | hardik | 27 | bhopal | 8500.00 |
| 6 | komal | 22 | mp | 4500.00 |
| 7 | muffy | 24 | indore | 10000.00 |
---- ---------- ----- ----------- ----------
----- --------------------- ------------- --------
|oid | date | customer_id | amount |
----- --------------------- ------------- --------
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
----- --------------------- ------------- --------
现在,让我们使用 left join 连接这两个表,如下所示。
sql> select id, name, amount, date
from customers
left join orders
on customers.id = orders.customer_id;
结果如下:
---- ---------- -------- ---------------------
| id | name | amount | date |
---- ---------- -------- ---------------------
| 1 | ramesh | null | null |
| 2 | khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | hardik | null | null |
| 6 | komal | null | null |
| 7 | muffy | null | null |
---- ---------- -------- ---------------------