MySQL 組合索引不生效

小彭友發表於2019-09-16

表名: 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執行結果:

mysql組合索引不生效

mysql組合索引不生效
SQL2執行結果:

mysql組合索引不生效

mysql組合索引不生效
結果: SQL1未用到索引,SQL2用到了索引,倆者查詢條件只有loaction_id不同。
分析: 資料總量大概在42萬左右,SQL1查出來的資料總量20萬,佔了總資料約等於50%,而SQL2查出來的資料佔比就很小,SQL1 type 為ALL,說明使用了全表搜尋,未用到索引,而SQL2使用到了之前的索引,type為range,效率大大提升了很多。
總結: 當查詢資料量/總資料量>20%左右,組合索引就用不到。
大家看了過後,如有不正確的地方請糾正一下,上述是自己親自測試,如果是其他原因,還請補充

相關文章