繁体   English   中英

选择相关表中没有值的记录的所有行

[英]Select all rows where related table has no records with value

我有桌子:

人表

ID  NAME
1   Matt
2   Josh

文件表

FILE_ID     PERSON_ID   TYPE
1           1           Photo
2           2           Text
3           2           Text

我想返回所有其他人,这些人在另一个表中没有任何照片类型的文件。

在上述情况下,我想返回:

ID  NAME
2   Josh

最有效的方法是什么?

我会使用not exists

select p.*
from person p
where not exists (select 1
                  from files f
                  where f.person_id = p.id and f.type = 'Photo'
                 );

为了提高性能,您需要在files(person_id, type)上建立索引。

我会使用not exists

select p.*
from person p
where not exists (select 1 from files f where f.person_id = p.id and f.type = 'photo');

not in使用

select p.*
from person p
where p.id not in (select id from Files f where f.type = 'photo');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM