[英]How to select from a table where column not exists in another table
table A 表A.
id city
1 koronadal
2 cebu
3 manila
Table B 表B.
id city
1 cebu
Expected ouput: 预期产量:
id city
1 koronadal
3 manila
Here is my query: 这是我的查询:
Select a.id, a.city from tablea a left join tableb b on a.city = b.city
I get the wrong output.. please help me.. 我得错了输出..请帮帮我..
You are on the right way! 你是正确的方式! now you just need to filter those who match :
现在你只需要过滤那些匹配的人:
Select a.id, a.city
from tablea a
left join tableb b
on a.city = b.city
WHERE b.id is null
In LEFT JOINING
when there is no match of the join condition, the left table, in this case tableA will still be selected, and all the data from the right table, in this case tableB will be NULL
. 在
LEFT JOINING
当连接条件不匹配时,左表,在这种情况下tableA仍将被选中,右表中的所有数据,在本例中为tableB将为NULL
。 So all you need to do is search for null values on B table. 所以你需要做的就是在B表上搜索空值。
Another approach would be to use IN()
: 另一种方法是使用
IN()
:
SELECT * FROM TableA a
WHERE a.city NOT IN(SELECT city FROM TableB)
And another way is EXISTS()
: 另一种方式是
EXISTS()
:
SELECT * FROM TableA a
WHERE NOT EXISTS(SELECT 1 FROM TableB b
WHERE a.city = b.city)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.