SQL Union子句优化

时间:2017-07-10 20:57:16

标签: sql oracle performance query-optimization

如果我的查询如下,如何优化它以更快地运行? thingstables是不变的。 different_tables是另一组表格。

Select * from (
    select things from tables where condition 1
    Union
    select things from tables where condition 2
    union
    select things from tables where condition 3
    union
    select things from different_tables where condition 4
    union 
    select things from different_tables where condition 5
)

1 个答案:

答案 0 :(得分:3)

为什么有这么多工会?

对于初学者,我们可以使用IN()语句显着减少工会数量。仅此操作将为您节省大量开销。它实际上相当于使用一系列or条件,但它更容易读写。

select * from (
  select things from tables where condition in (1,2,3)
  union
  select things from different_tables where condition in (4,5)
)

条件是否已编入索引?

如果condition未编入索引,则应考虑将其编入索引。

为什么派生表?

在您发布的示例中,没有理由使用派生表,只需使用

select things from tables where condition in (1,2,3)

union

select things from different_tables where condition in (4,5)

应该足够了

具有更复杂的where子句的示例。

select 
  things 
from 
  tables 
where 
  condition_1 in (1,2,3)
  or condition_2 = 4
  or (
    condition_1     = 1
    and condition_3 = 5
  )

上面的示例显示了一个查询,如果满足三个主要条件中的任何一个,它将提取记录。如果您在同一张桌子上操作,您仍然可以合并查询。