简体   繁体   English

如何从另一个表中不存在列的表中进行选择

[英]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.

相关问题 从一个表中选择另一个表中存在列值的记录 - Select records from one table where a column value exists in another table 从存在ID(从另一表)的一个表中选择 - Select from one table where id (from another table) exists 如何 select 来自 table1 的记录,其中 table1.id 存在于 table2 的 id 列中? - How to select the records from a table1 where table1.id exists in id column of table2? MYSQL SELECT WHERE子句:如何包含另一个表中的列? - MYSQL SELECT WHERE Clause : How to include a column from another table? 如何选择一个表中存在ID的行,而另一表中没有ID? - How to select rows where the ID exists in one table, but not another? 如何从一个表中选择一列,从另一个表中选择另一列 - How to select a column from a table and another column from another table 如何从多对多表中选择一个ID,而另一个ID中不存在的记录呢? - How to select a record from a many to many table where one id exists in one but not another? MYSQL仅在该表的列值与另一表的列值匹配的情况下,才如何从该表中选择数据? - MYSQL How do I select data from one table only where column values from that table match the column values of another table? 如何从一个表中选择与表中的列值相匹配的数据? - How do I select data from one table where column values from that table match the conatenated column values of another table? 从一个表中选择行,其中从另一个表中的数组中存在值 - select row from one table where value exists from array from another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM