看到一篇文章是講sql語句or與union all的執行效率比較的,之前沒怎麼注意這個問題,感受文章寫的不錯,轉來一看。sql
文章原連接:http://www.cunyoulu.com/zhuanti/qtstudy/20081124orunion.htm測試
sql語句or與union all的執行效率比較優化
當SQL語句有多個or語句時,能夠考慮使用union或者union all代替來提升速度。使用or的SQL語句每每沒法進行優化,致使速度變慢。但這不是固定的,有時候使用or速度會更快些。具體狀況還要通過測試爲準。若是加索引的話,也可能實現速度優化。htm
實驗表格以下,實際數據有2,000,000條,從裏面返回大約最多1000行左右的數據。索引
X | Y | Inline | CDP | T |
12002400 | 5801000 | 300 | 300 | 3400 |
12002408 | 5801005 | 300 | 301 | 3402 |
12002416 | 5801010 | 300 | 302 | 3404 |
12002424 | 5801015 | 300 | 303 | 3406 |
... | ... | ... | ... | ... |
or語句(部分節選)get
SELECT * FROM tablename where (cdp= 300 and inline=301) or (cdp= 301 and inline=301) or (cdp= 302 and inline=301) or (cdp= 303 and inline=301) or (cdp= 304 and inline=301) or (cdp= 305 and inline=301) or (cdp= 306 and inline=301) or (cdp= 307 and inline=301)qt
union all語句(部分節選)io
SELECT * FROM tablename where (inline= 300 and cdp=300) union all SELECT * FROM tablename where (inline= 301 and cdp=300) union all SELECT * FROM tablename where (inline= 302 and cdp=300) union all SELECT * FROM tablename where (inline= 303 and cdp=300)table
返回不規則的900條數據,前者用了60多秒,後者用了8秒左右。效率