sql - 如何选择在其子表中没有特定值的表的不同 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”规范的所有自动服务?(第二个表是第一个表的子表)
解决方案
使用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)
。
推荐阅读
- python - 正则表达式从匹配的下一个字符开始
- c# - 需要获取从 AutoCAD Civil3D 中的类创建的对象的计数
- notepad++ - 记事本++多个数字和字符交换
- excel - 使用一个切片器更改 Excel 表和数据透视表数据
- c# - 如何动态设置 DatePicker 的值?
- spring-boot - 单独项目中的 Spring AOP
- c++ - 如何根据第一个字符和第三个字符将字符串读入 C++ 中的二维字符串数组
- mvvmcross - 如何绑定事件流式API mvvmCross
- reactjs - npm(反应导航)模块未更新
- amazon-web-services - 如何允许来自 VPN 的流量访问内部负载均衡器 (AWS)?