MySQL的or/in/union與索引優化

轉載自:MySQL的or/in/union與索引優化 https://blog.csdn.net/zhangweiwei2020/article/details/80005590html

假設訂單業務表結構爲:程序員

order(oid, date, uid, status, money, time, …)post

其中:優化

  • oid,訂單ID主鍵ui

  • date,下單日期,有普通索引,管理後臺常常按照date查詢spa

  • uid,用戶ID,有普通索引,用戶查詢本身訂單.net

  • status,訂單狀態,有普通索引,管理後臺常常按照status查詢code

  • money/time,訂單金額/時間,被查詢字段,無索引htm

--假設訂單有三種狀態:0已下單,1已支付,2已完成

--如下查詢未完成的訂單,哪一個SQL更快呢?
--方案1
    select * from order where status!=2
--方案2
    select * from order where status=0 or status=1
--方案3
    select * from order where status IN (0,1)
--方案4
    select * from order where status=0
    union all
    select * from order where status=1

--結論:方案1最慢,方案2,3,4都能命中索引

一:union all 確定是可以命中索引的blog

--方案4
select * from order where status=0
union all
select * from order where status=1

說明:

  • 直接告訴MySQL怎麼作,MySQL耗費的CPU最少

  • 程序員並不常常這麼寫SQL(union all)

二:簡單的in可以命中索引

--方案3
select * from order where status in (0,1)

說明:

  • MySQL思考,查詢優化耗費的cpuunion all多,但能夠忽略不計

  • 程序員最常這麼寫SQL(in),這個例子,最建議這麼寫

三:對於or,新版的MySQL可以命中索引

--方案2
select * from order where status=0 or status=1

說明:

  • MySQL思考,查詢優化耗費的cpuin多,別把負擔交給MySQL

  • 不建議程序員頻繁用or,不是全部的or都命中索引

  • 對於老版本的MySQL,建議查詢分析下

4、對於!=,負向查詢確定不能命中索引

--方案1
select * from order where status!=2

說明:

  • 全表掃描,效率最低全部方案中最慢

  • 禁止使用負向查詢

5、其餘方案

--其餘
select * from order where status < 2

這個具體的例子中,確實快,可是:

  • 這個例子只舉了3個狀態,實際業務不止這3個狀態,而且狀態的「值」正好知足偏序關係,萬一是查其餘狀態呢,SQL不宜依賴於枚舉的值,方案不通用

  • 這個SQL可讀性差,可理解性差,可維護性差,強烈不推薦

相關文章
相關標籤/搜索