优化查询以获取其他表中不存在的 ID
Optimized query to get IDs not present in other tables
我有三张桌子。 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'
仅使用集合运算符:
SELECT t1.id
FROM t1
WHERE t1.col2 = 'A'
MINUS
(SELECT t2.id FROM t2
UNION
SELECT t3.id FROM t3
);
我会使用 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)
我有三张桌子。 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'
仅使用集合运算符:
SELECT t1.id
FROM t1
WHERE t1.col2 = 'A'
MINUS
(SELECT t2.id FROM t2
UNION
SELECT t3.id FROM t3
);
我会使用 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)