簡體   English   中英

SQL Union子句優化

[英]SQL Union Clause 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
)

為什么會有那么多工會?

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

上面的示例顯示了一個查詢,該查詢將在滿足三個主要條件中的任何一個條件時提取記錄。 如果您在同一個表上進行操作,那么您仍然應該可以合並查詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM