v7.x版本聚合查询执行计划不准确

【TiDB 使用环境】生产环境
【TiDB 版本】v7.5.6
【遇到的问题:问题现象及影响】
近期升级的新集群版本为v7.5.6,该版本执行一些聚合查询或者大范围统计查询时,更加偏爱走全表扫描。而低版本v4.x、5.x集群,会根据统计信息选择走合适的索引
表结构

CREATE TABLE `merchant_assessment_day_warn_detail` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `index_key` varchar(128) NOT NULL DEFAULT '',
  `merchant_id` bigint(20) NOT NULL DEFAULT '0' ,
  `cycle_date` int(8) NOT NULL DEFAULT '0' ,
  `statistics_date` int(8) NOT NULL DEFAULT '0' ,
  `index_code` bigint(20) NOT NULL DEFAULT '0' ,
  `overall_score` bigint(20) NOT NULL DEFAULT '0' ,
  `avg_indicator` bigint(20) NOT NULL DEFAULT '0' ,
  `indicator_detail` varchar(1024) NOT NULL DEFAULT '' ,
  `category_indicator_detail` varchar(8192) NOT NULL DEFAULT ' ',
  `extend_detail` varchar(1024) NOT NULL DEFAULT '' ,
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `merchant_type` int(4) NOT NULL DEFAULT '0' ,
  `data_version` varchar(8) NOT NULL DEFAULT '' ,
  PRIMARY KEY (`id`),
  KEY `idx_create_time` (`create_time`),
  KEY `idx_update_time` (`update_time`),
  UNIQUE KEY `uk_merchant_id_statistics_date_cycle_date_index_code` (`merchant_id`,`statistics_date`,`cycle_date`,`index_code`),
  KEY `idx_index_key` (`index_key`)
);

执行SQL

select statistics_date,count(1) from merchant_assessment_day_warn_detail where create_time between '2025-08-20 00:00:00' and '2025-09-09 00:00:00' group by statistics_date order by statistics_date;

v4.0.11集群
执行耗时:12秒


执行计划

v7.5.6集群
健康度

执行耗时:2分32.78秒

执行计划


analyze table刷新下统计信息呢

刷新了,也没用。

我试了下。7.5.6下执行计划确实有问题。需要加hint

explain
select statistics_date,count(1)
from merchant_assessment_day_warn_detail use index(idx_create_time)
where create_time between ‘2025-08-20 00:00:00’ and ‘2025-09-09 00:00:00’
group by statistics_date
order by statistics_date;

加个use index就变回来了。另外最新版本v8.5.3下,执行计划也是对的。感觉就是你这个子版本的一些特定的优化问题。

还有,如果这个sql访问并发不高且有tiflash的情况下,你这个sql也特别适合tiflash+mpp执行,速度可能比12秒还要快一些,提升到1-2s也是有可能的。如果你已经有tiflash资源的情况下,务必考虑一下这个方式。

v4.x、v5.x的版本我都测试过,可以正常选择走范围查询,只有v7.x上,默认就走全表扫。线上已经多次SQL走错索引导致应用抖动,遇到了只能通过SPM进行绑定。
当前集群中,只有一个集群有tiflash,还在灰度阶段。

1 个赞

猜测有可能是 https://docs.pingcap.com/zh/tidb/stable/system-variables/#tidb_opt_objective-从-v740-版本开始引入 导致的,可以看一下是不是都是这种开闭范围的,由于统计信息缺少,导致容易越界,可以试试 session 级别改改参数值,看看有没有效果。如果有,可以考虑集群设置参数值。

1 个赞

效果相当明显。

1 个赞

来一份 plan replayer

done

statistics_date,create_time 搞个联合索引

是大佬

此话题已在最后回复的 7 天后被自动关闭。不再允许新回复。