我有两个表与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)
的索引。
下面是使用连接的查询 -
SELECT
F1.ServiceId,
F2.Name
from table1 t1
LEFT OUTER JOIN table2 t2
ON t1.serviceid=t2.serviceid
WHERE t2.NAME <> 'AUTH';
使用存在
SELECT t1.serviceid,
t2.NAME
FROM table1 t1
WHERE EXISTS (SELECT serviceid,
NAME
FROM table2 t2
WHERE t1.serviceid = t2.serviceid
AND t2.NAME <> 'AUTH')
希望这可以帮助
这个查询:
select distinct serviceid from specialities where name = 'AUTH'
返回表distinct serviceid
中specialities
列中包含'AUTH'的所有name
s。
所以你只需要从serviceid
表中排除这些auto_services
s,
像这样的left join
:
select * from auto_services a left join (
select distinct serviceid from specialities where name = 'AUTH'
) s on s.serviceid = a.serviceid
where s.serviceid is null
或与not in
:
select * from auto_services
where serviceid not in (
select distinct serviceid from specialities where name = 'AUTH'
)