SQL:从2个表中选择不匹配的记录



我有两个表,我想从第一个表中检索id_apartment没有出现在第二个表中的行:

id | id_floor | id_apartment 
----+----------+--------------
1 |        0 |          101
2 |        1 |          101
3 |        1 |          102
4 |        1 |          103
5 |        1 |          104
6 |        2 |          201
7 |        2 |          202
8 |        2 |          203

table2.id | table2.guest | table2.apartment_id
----+---------------+--------------
1 |         65652 |          101
2 |         65653 |          101
3 |         65654 |          101
4 |         65655 |          101
5 |         65659 |          102
6 |         65656 |          201
7 |         65660 |          202
8 |         65661 |          202
9 |         65662 |          202
10 |         65663 |          203

预期输出:

floor | number
-------+--------
1 |    103
1 |    104

我尝试使用LEFT、INNER和RIGHT联接,但总是得到EMPTY结果。我该如何处理?

您可以使用not exists:

select *
from table1 t1
where not exists(
select 1
from table2 t2
where t1.id_apartment = t2.apartment_id
)

正则解是not exists:

select t1.*
from table1 t1
where not exists (select 1 from table2 t2 where t2.apartment_id = t1.id_apatment);

然而,这也将返回第一个表中的1以及103104的值。

我不知道你是想在floor上进行额外的过滤,还是数据只是问题中的错误。

一个快速解决方案是使用not in

Select * from table_1 where table_1.id_apartment not in (select apartment_id from table_2)

您可以在此处使用左反联接:

SELECT t1.*
FROM table1 t1
LEFT JOIN table2 t2
ON t1.id_apartment = t2.apartment_id
WHERE
t2.apartment_id IS NULL;

但现有的逻辑应该同样有效,而且实际上更接近于您需求的字面翻译。

让第一个表的名称为table1,第二个表的名字为table2

你的问题的答案是:

select * from table1 t1 
where t1.id_apartment <> all (select t2.apartment_id from table2 t2 )

最新更新