使用 explain 如何判断二级索引使用后是否回表?

使用 explain 如何判断二级索引使用后是否回表?

数据库 2024-11-12 17:05:16 9个月前

如何使用 explain 判断二级索引使用后,是否存在回表操作?

对于给定的查询 sql:

select    track_source_id,    date_format(created_at, '%y-%m-%d') as day,    count(*) as total_count,    sum(case when len_parse_result_list = 0 then 1 else 0 end) as len_parse_result_list_zero_count,    sum(case when len_parse_result_list is null then 1 else 0 end) as len_parse_result_list_null_count,    sum(case when len_parse_result_list > 0 then 1 else 0 end) as len_parse_result_list_gte_zero_countfrom    keywordtaskwhere    created_at >= now() - interval 30 daygroup by    track_source_id,    dayorder by    track_source_id,    day;

其 explain 输出:

| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra || --- | ----------- | ----- | ---------- | ---- | ------------- | --- | ------ | --- | ---- | -------- | ----- || 1   | SIMPLE      | keywordtask | NULL      | index | idx_created_at,idx_track_source_id_created_at_len_parse_result_list | idx_track_source_id_created_at_len_parse_result_list | 14 | NULL | 134324154 | 50.0 | Using where; Using index; Using temporary; Using filesort |

是否回表判断:

通过读取 extra 列,可以判断查询是否回表:

using index 表示索引覆盖,不需要回表。using index condition 表示索引查找,不需要回表过滤。using index & using where 表示索引查找,但需要回表过滤。using where 表示回表查询数据。主键查询 不回表,但 extra 列无法反映。

对于给定的查询,extra 列为 using where; using index; using temporary; using filesort,表明查询使用了索引 (idx_track_source_id_created_at_len_parse_result_list),但需要回表过滤条件 created_at >= now() - interval 30 day。因此,该查询会发生回表操作。

文章版权声明:除非注明,否则均为网络转载文章,转载或复制请以超链接形式并注明出处。