ORDER BY id 爲什麼效率不高

ORDER BY id 爲什麼效率不高

背景

系統代碼中有如下查詢SQL,DBA要求優化;mysql

SELECT id,
user_id,
patient_id,
his_id,
bill_no,
log_model
FROM platfom_fee_log
WHERE fee_channel = 2
AND gmt_create >= '2018-12-24 01:05:00'
AND gmt_create <= '2018-12-25 07:58:00'
AND (id_no = '370281198211092363' OR guarder_id_no = '370281198211092363')
ORDER BY id DESC
LIMIT 0,10

DBA驗證的結論:sql

上述 sql 須要優化,如今 200s 返回,優化後 0.54s。order by id 改成 order by gmt_create優化

思考點

爲何order by id不行,而 order by gmt_create 效果更好?google

DBA給出緣由爲:.net

order by id,mysql 的優化器會選擇主鍵索引,可是 where 條件裏又沒有主鍵條件,致使全表掃描。
order by gmt_create,結合 where 條件裏 gmt_create ,mysq 優化器會選擇 gmt_create 索引,掃描的記錄數少,效果更好。

知其然知其因此然

這篇博客中有進一步的解釋;code

更多詳見Googleblog

相關文章
相關標籤/搜索