SQL 联合子句优化



如果我的查询如下,如何优化它以更快地运行?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
)

为什么有这么多工会?

首先,我们可以通过使用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
)

上面的示例显示了一个查询,如果满足三个主要条件中的任何一个,该查询将拉取记录。如果在同一表上操作,则仍应能够组合查询。

最新更新