我很难理解为什么LEFT JOIN / IS NULL会消除一个表中的记录而不会记录另一个表中的记录.
这是一个例子
SELECT l.id, l.value
FROM t_left l
LEFT JOIN t_right r
ON r.value = l.value
WHERE r.value IS NULL
为什么r.value = NULL会消除记录?我不理解 .我知道我遗漏了一些非常基本的东西,但目前我甚至无法弄清楚那个基本的东西.如果有人向我详细解释,我将不胜感激.
我想要一个非常基本的解释.
解决方法:
这可以用以下内容解释
mysql> select * from table1 ;
+------+------+
| id | val |
+------+------+
| 1 | 10 |
| 2 | 30 |
| 3 | 40 |
+------+------+
3 rows in set (0.00 sec)
mysql> select * from table2 ;
+------+------+
| id | t1id |
+------+------+
| 1 | 1 |
| 2 | 2 |
+------+------+
2 rows in set (0.00 sec)
这里table1.id< - > table2.t1id
现在,当我们使用连接键进行左连接时,如果左表是table1,那么它将获得table1中的所有数据,并且table2上的非匹配记录将被设置为null
mysql> select t1.* , t2.t1id from table1 t1
left join table2 t2 on t2.t1id = t1.id ;
+------+------+------+
| id | val | t1id |
+------+------+------+
| 1 | 10 | 1 |
| 2 | 30 | 2 |
| 3 | 40 | NULL |
+------+------+------+
3 rows in set (0.00 sec)
看到table1.id = 3在table2中没有值,所以它设置为null
当您应用where条件时,它将进行进一步过滤
mysql> select t1.* , t2.t1id from table1 t1
left join table2 t2 on t2.t1id = t1.id where t2.t1id is null;
+------+------+------+
| id | val | t1id |
+------+------+------+
| 3 | 40 | NULL |
+------+------+------+
1 row in set (0.00 sec)