select count(*) from trade where shippingtype <> "free" and status
in ("TRADE_FINISHED","WAIT_SELLER_SEND_GOODS") and tosellerreachgoods = 0 and consigntime <1470110400000 and ( endtime >=1469980800000 or endtime is null ) and created >=1469980800000 and created <=1470067200000 and user = "xxxxxxxxxxxxxxxx" ;
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | trade | range | trade__user,trade_user_created,trade_user_buyernick,trade__status_created,trade_user_status | trade_user_created | 108 | NULL | 588 | Using index condition; Using where |
阿神2017-04-17 15:21:32
儘管從explain結果看這個查詢沒什麼特別問題,但以下幾點可以考慮一下。
1、shippingtype
和status
看起來是個枚舉值,可以用tinyint
代替(數值查詢比字串查詢速度要快);
2、endtime
設為NOT NULL
, 把原來的null值用一個特殊值(-1或0)代替,NULL
值會影響索引的效率;
3、可以的話,用user_id
代替user
;
個人YY的最佳化:
SELECT count(*) FROM trade
WHERE status IN ("TRADE_FINISHED", "WAIT_SELLER_SEND_GOODS")
AND shippingtype <> "free"
AND tosellerreachgoods = 0
AND user = "xxxxxxxxxxxxxxxx"
AND consigntime < 1470110400000
AND created BETWEEN 1469980800000 AND 1470067200000
AND ( endtime >= 1469980800000 OR endtime IS NULL );
前面4個條件沒什麼好說的,主要是後面三個條件,分別是consigntime
、created
和endtime
,根據篩選範圍從小到大來排列(具體要看你的表裡這三個欄位的範圍段)。
部分建議是基於你能修改表格結構的基礎上提出的,如果沒有權限的話那就忽略吧。
參考資料:http://tech.meituan.com/mysql...