看到一篇文章是讲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秒左右。效率