mysql left join 會取得左表的全部數據,即使右表並無完全匹配的結果
d表:
[yoon]> select * from d; +----+----------+------+
| id | number | name |
+----+----------+------+
| 1 | 12345 | aa |
| 3 | 123456 | aa |
| 5 | 1234567 | aa |
| 7 | 12345678 | aa |
+----+----------+------+
hank表:
[yoon]> select * from hank; +----+------+------+-----+
| id | name | cc2 | cc3 |
+----+------+------+-----+
| 1 | YOON | NULL | 0 |
| 3 | CEV | NULL | 0 |
| 4 | AAA | NULL | 0 |
| 5 | CCC | NULL | 0 |
+----+------+------+-----+
left join
[yoon]> select d.id,d.number,hank.cc3 from d left join hank on d.id = hank.id; +----+----------+------+
| id | number | cc3 |
+----+----------+------+
| 1 | 12345 | 0 |
| 3 | 123456 | 0 |
| 5 | 1234567 | 0 |
| 7 | 12345678 | NULL |
+----+----------+------+ Using 相當於 on,如下: [yoon]> select d.id,d.number,hank.cc3 from d left join hank using(id); +----+----------+------+
| id | number | cc3 |
+----+----------+------+
| 1 | 12345 | 0 |
| 3 | 123456 | 0 |
| 5 | 1234567 | 0 |
| 7 | 12345678 | NULL |
+----+----------+------+
IS NULL:
在上面語句中,右表中沒有對應匹配的記錄,其所有列都被置為 NULL ,因此要查詢這部分數據,可以通過 where is null 來查詢
[yoon]> select d.id,d.number,hank.cc3 from d left join hank using(id) where hank.id is null; +----+----------+------+
| id | number | cc3 |
+----+----------+------+
| 7 | 12345678 | NULL |
+----+----------+------+ 或 [yoon]> select d.id,d.number,hank.cc3 from d left join hank on d.id = hank.id where hank.id is null; +----+----------+------+
| id | number | cc3 |
+----+----------+------+
| 7 | 12345678 | NULL |
+----+----------+------+
說明: hank.id is null 查詢的是不匹配的值, hank.id is not null 查詢的就是匹配到的值,如下:
[yoon]> select d.id,d.number,hank.cc3 from d left join hank on d.id = hank.id where hank.id is not null; +----+---------+------+
| id | number | cc3 |
+----+---------+------+
| 1 | 12345 | 0 |
| 3 | 123456 | 0 |
| 5 | 1234567 | 0 |
+----+---------+------+