【问题标题】:Optimized query to get IDs not present in other tables优化查询以获取其他表中不存在的 ID
【发布时间】:2020-12-09 18:27:39
【问题描述】:

我有三张桌子。 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'

【问题讨论】:

  • 更多的是关于执行计划,它取决于您的数据分布和所有 3 个表的基数。通常在所有大表的情况下,最好得到2个hash join anti,所以通常not exists、not in和left join x where x.id is null比设置运算符好(设置加入转换默认禁用,默认启用仅适用于最新的 oracle 版本)
  • 向我们展示以下 3 个查询的结果:1. Select count(*), count(distinct ID) from t1 where col2 ='A' 2) select count(*), count(distinct ID) from t2 3) select count(*), count(distinct ID) from t3

标签: sql oracle oracle11g subquery query-optimization


【解决方案1】:

我会使用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)

【讨论】:

    【解决方案2】:

    只使用集合运算符:

    SELECT t1.id
      FROM t1
     WHERE t1.col2 = 'A'
    MINUS
    (SELECT t2.id FROM t2
     UNION
     SELECT t3.id FROM t3
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 2012-01-29
      • 1970-01-01
      • 2015-07-22
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多