问题描述
我有三个桌子。 T1是主机,并存储唯一的ID。 我想获取在t2和t3中不存在但在t1中存在的ID 我写了一个查询。不知道它是否正确并对其进行了优化。由于所有表中都有大量数据,因此需要以更好的方式来编写查询。
Select t1.ID
from t1
where ID not in (
Select distinct t2.ID from t2
Union
Select distinct t3.ID from t3
)
and col2 ='A'
解决方法
我会使用not exists
:
select t1.*
from t1
where
col2 = 'A'
and not exists(select 1 from t2 where t2.id = t1.id)
and not exists(select 1 from t3 where t3.id = t1.id)
此查询应使以下索引受益:
t1(col2,id)
t2(id)
t3(id)
,
仅使用集合运算符:
SELECT t1.id
FROM t1
WHERE t1.col2 = 'A'
MINUS
(SELECT t2.id FROM t2
UNION
SELECT t3.id FROM t3
);