首页 > 解决方案 > 如何选择在其子表中没有特定值的表的不同 ID?

问题描述

我有两个具有 1-n 关系的表。其中一个是汽车服务表,另一个有它们的规格,例如;

 ID   ServiceId    Name  
---------------------------             
 1     FJ12        Fletcher Jones     
 2     HS35        Hardy's
 3     YK65        Yorker

SpecialityID   ServiceID    Name
---------------------------------
1              FJ12         AUTH
2              FJ12         PRIV
3              FJ12         GRS
4              HS35         PRIV
5              HS35         AUTH
6              HS35         CRS
7              YK65         PRIV
8              HS35         GRS

我尝试了一些左外连接查询和 where 子句,但我无法处理。如何从第一个表中获取第二个表中没有“AUTH”规范的所有自动服务?(第二个表是第一个表的子表)

标签: sqlselect

解决方案


使用NOT EXISTS

select aus.*
from auto_services aus
where not exists (select 1
                  from specifications s
                  where s.serviceId = aus.serviceId and
                        s.name = 'AUTH'
                 );

为了性能,您需要在索引中specifications(serviceId, name)


推荐阅读