​​

sql语句or与union all的执行效率比较

    当SQL语句有多个or语句时,可以考虑使用union或者union all代替来提高速度。使用or的SQL语句往往无法进行优化,导致速度变慢。但这不是固定的,有时候使用or速度会更快些。具体情况还要经过测试为准。如果加索引的话,也可能实现速度优化。

    实验表格如下,实际数据有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语句(部分节选)

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)

union all语句(部分节选)

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)

返回不规则的900条数据,前者用了60多秒,后者用了8秒左右。