优化查询以获取其他表中不存在的ID

问题描述

我有三个桌子。 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
);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...