您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Left Join / IS NULL如何消除一个表中存在而另一表中没有的记录?

Left Join / IS 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

现在,当我们leftjoin使用连接键进行操作时,如果左边的表是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)
其他 2022/1/1 18:38:51 有372人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶