检查索引是否命中:EXPLAIN
//create_time无效索引
EXPLAIN SELECT * FROM yx_store_product_pink_big_detail WHERE DATE(create_time) = '2024-06-10';
//create_time无效索引
EXPLAIN SELECT * from yx_store_product_pink_big_detail where DATE_FORMAT(create_time,"%Y-%m-%d")='2024-06-10'
//create_time有效索引
EXPLAIN SELECT * from yx_store_product_pink_big_detail WHERE create_time >= '2024-06-06' AND create_time <'2024-06-06' + INTERVAL 1 DAY and is_del=0 and pink_id=21807;
当你使用 EXPLAIN
来分析查询时,关键信息是 type
列和 key
列。type
列显示了连接类型,而 key
列则显示了查询优化器是否决定使用某个索引。
如果 key
列有值,那么表示查询使用了索引。这个值通常是索引的名称。如果 key
列的值为 NULL
,则表示查询没有使用索引,可能会进行全表扫描。
type
列的值也给出了查询如何执行的一些线索。对于高效的查询,通常希望看到 range
、ref
、eq_ref
、const
或 system
等类型,这些类型通常表示查询优化器能够使用索引来限制需要检查的行数。
查询所有索引
SHOW INDEX FROM yx_store_product_pink_big_detail;
查询本周数据create_time有效索引案例
EXPLAIN
SELECT *
FROM yx_store_product_pink_big_detail
WHERE is_del = 0
AND create_time >= DATE_SUB('2024-06-13', INTERVAL WEEKDAY('2024-06-13') DAY)
AND create_time < DATE_ADD(DATE_SUB('2024-06-13', INTERVAL WEEKDAY('2024-06-13') DAY), INTERVAL 7 DAY);
查询本月数据create_time有效索引案例
EXPLAIN SELECT * FROM yx_user_release_details
WHERE is_del = 0 and uid=16666
AND create_time >= DATE_FORMAT('2024-06-24 14:10:24', '%Y-%m-01') AND create_time < DATE_ADD(LAST_DAY('2024-06-24 14:10:24'), INTERVAL 1 DAY)