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

相关文章
相关标签/搜索