MySQL 组合索引不生效
表名: y_capture_photo_new_2019_09
索引: INDEX_LOCATION_CREATED_HUMAN(location_id, created_at, humanoid_num)
SQL1:
select `id`, `capture_photo_path` from `y_capture_photo_new_2019_09` where `created_at` between '2019-09-01 00:00:00' and '2019-09-11 23:59:59' and `location_id` in ('1535', '1536', '1537', '1538', '1539', '1540', '1541', '1542', '1543', '1544', '1545', '1546', '1559') and `humanoid_num` > '1'
SQL2:
select `id`, `capture_photo_path` from `y_capture_photo_new_2019_09` where `created_at` between '2019-09-01 00:00:00' and '2019-09-11 23:59:59' and `location_id` in ('1687', '1688', '1689', '1690', '1692', '1693', '1695', '1696', '1698', '1699', '1700', '1701', '1703', '1704', '1705', '1707', '1708', '1710', '1711', '1713', '1717', '1719', '1720', '1721', '1722', '1723') and `humanoid_num` > '1'
SQL1执行结果:
SQL2执行结果:
结果: SQL1未用到索引,SQL2用到了索引,俩者查询条件只有loaction_id不同。
分析: 数据总量大概在42万左右,SQL1查出来的数据总量20万,占了总数据约等于50%,而SQL2查出来的数据占比就很小,SQL1 type 为ALL,说明使用了全表搜索,未用到索引,而SQL2使用到了之前的索引,type为range,效率大大提升了很多。
总结: 当查询数据量/总数据量>20%左右,组合索引就用不到。
大家看了过后,如有不正确的地方请纠正一下,上述是自己亲自测试,如果是其他原因,还请补充!
本作品采用《CC 协议》,转载必须注明作者和本文链接
sql2 比 sql1 最后多了一个
)
是什么意思?@轻描淡写 已修改,细,你真细 :grin:
@小彭友 :oncoming_automobile: