Oracle SQL查询性能改进:减与不存在

Ion*_*n C 1 sql oracle query-optimization

我需要提高此查询的性能:

Select 
   t1.column1, t1.column2 
From
   table1 t1, table2 t2
Where 
   t1.id = t2.id and
   t1.some_column = t2.some_column
--------
minus
--------
Select 
   t1.column1, t1.column2 
From
   table1 t1, table2 t2, table3 t3
Where 
   t1.id = t2.id and
   t1.some_column = t2.some_column and
   t1.id = t3.id
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用“不存在”而不是“减号”重写此查询。有人可以给我建议吗?

bpg*_*rgo 5

这个怎么样?

Select 
   t1.column1, t1.column2 
From
   table1 t1, table2 t2
Where 
   t1.id = t2.id
   and t1.some_column = t2.some_column
   and not exists (select 1 from table3 t3 where t1.id = t3.id)
Run Code Online (Sandbox Code Playgroud)


Ger*_*ima 5

这取决于第一个查询和 table3 之间的比例大小/#-of-rows:

  • 如果表3有许多行,我可能会使用@bpgergo的解决方案,因为它仅需要运行除了查询少数几次,它应该是快的(我假设有在ID索引);
  • 如果 table3 有行,我会使用以下解决方案,因为子查询可以一次运行并在内存缓存中进行匹配:
SELECT t1.column1, t1.column2
FROM table1 t1, table2 t2
WHERE t1.id = t2.id
AND t1.some_column = t2.some_column
AND t1.id NOT IN (SELECT t3.id FROM table3 t3);
Run Code Online (Sandbox Code Playgroud)

两种解决方案都受益于每个表id列上的索引,如果是这种情况,还可以id从用于过滤第一个查询的列上的附加索引(或包含 的复合索引)中受益。