優化mysql中where or和where in語句的效率

1、使用union來取代where in:

使用where or語句操做:
select * from city where id = 1 or id = 3 or id = 4
輸出:
1 廣州
3 深圳
4 惠州
explain 結果:
id select_type table type possible_keys key key_len ref rows Extra
1   SIMPLE       city   ALL    PRIMARY       NULL NULL     NULL 5     Using where 性能


標準使用where in操做:
select * from city where id in (1,3,4)
輸出:
1 廣州
3 深圳
4 惠州
explain 結果:
id select_type table type possible_keys key key_len ref rows Extra
1   SIMPLE       city   ALL    PRIMARY       NULL NULL     NULL 5     Using where 排序

使用union all操做:
SELECT * FROM city where id = 1 union all SELECT * FROM city where id = 3 union all SELECT * FROM city ci

where id = 4
輸出:
1 廣州
3 深圳
4 惠州
explain 結果:
id   select_type table        type possible_keys key      key_len ref   rows Extra
1    PRIMARY      city         const PRIMARY       PRIMARY 4       const 1  
2    UNION        city         const PRIMARY       PRIMARY 4       const 1  
3    UNION        city         const PRIMARY       PRIMARY 4       const 1  
NULL UNION RESULT <union1,2,3> ALL   NULL          NULL     NULL    NULL NULL   it

使用union all而且支持order by (由於union不支持order by,使用如下方式則支持):
select * from (SELECT * FROM city where id = 1 order by id asc) as t1 UNION ALL select * from (SELECT * FROM city where id = 3 order by id desc) as t2 UNION ALL select * from city where id = 4
1 廣州
3 深圳
4 惠州 io

使用union all而且對最後的結果集進行排序:(本SQL使用了filesort,性能有下降)
select * from (select * from (SELECT * FROM city where id = 1 order by id asc) as t1 UNION ALL select * from (SELECT * FROM city where id = 3 order by id desc) as t2 UNION ALL select * from city where id = 4) as s1 order by id desc
輸出:
4 惠州
3 深圳
1 廣州 table


2、Union 和 Union all 的差別:
效率

UNION在進行表連接後會篩選掉重複的記錄,因此在表連接後會對所產生的結果集進行排序運算,刪除重複的記錄再返回 file

結果。實際大部分應用中是不會產生重複的記錄,最多見的是過程表與歷史表UNION。
union all 只是簡單的將兩個結果合併後就返回。這樣,若是返回的兩個結果集中有重複的數據,那麼返回的結果集就會包含重複的數據了。 select

從效率上說,UNION ALL 要比UNION快不少,因此,若是能夠確認合併的兩個結果集中不包含重複的數據的話,那麼就使用UNION ALL nio

查詢對比:

select rand(1) union select rand(2) union select rand(3);
輸出:
0.405403537121977
0.655586646549019
0.90576975597606


select rand(1) union select rand(1) union select rand(1);
輸出:0.405403537121977

select rand(1) union all select rand(1) union all select rand(1); 輸出: 0.405403537121977 0.405403537121977 0.405403537121977

相關文章
相關標籤/搜索