发现一句慢SQL
SELECT max( id ) FROM ua_ad_message WHERE task_id = ‘434362’
→ ;
±----------+
| max( id ) |
±----------+
| 390061695 |
±----------+
1 row in set (7.64 sec)
条件对应的数量
SELECT count() FROM ua_ad_message where task_id = ‘434362’;
±---------+
| count() |
±---------+
| 38392 |
±---------+
表索引
KEY idx_inner_batch_no_version
(inner_batch_no
,version
),
KEY idx_task_id_tel
(task_id
,tel
),
KEY idx_task_id_status
(task_id
,status
)
执行计划
explain SELECT max( id ) FROM ua_ad_message WHERE task_id = ‘434362’;
±-------------------------------±--------±----------±--------------------±---------------------------------------------------------+
| id | estRows | task | access object | operator info |
±-------------------------------±--------±----------±--------------------±---------------------------------------------------------+
| StreamAgg_10 | 1.00 | root | | funcs:max(tidb_mycat_onesms.ua_ad_message.id)->Column#22 |
| └─Limit_14 | 1.00 | root | | offset:0, count:1 |
| └─TableReader_23 | 1.00 | root | | data:Limit_22 |
| └─Limit_22 | 1.00 | cop[tikv] | | offset:0, count:1 |
| └─Selection_21 | 1.00 | cop[tikv] | | eq(tidb_mycat_onesms.ua_ad_message.task_id, 434362) |
| └─TableFullScan_20 | 4333.97 | cop[tikv] | table:ua_ad_message | keep order:true, desc |
±-------------------------------±--------±----------±--------------------±---------------------------------------------------------+
执行计划来看是走全表扫描,全表估算4333
手动执行analyze table后执行计划不变
指定索引解决
ELECT /*+ USE_INDEX(ua_ad_message, idx_task_id_status) */ max(id) FROM ua_ad_message WHERE task_id = ‘434362’;
±----------+
| max(id) |
±----------+
| 390061695 |
±----------+
全表数量
SELECT count() FROM ua_ad_message;
±---------+
| count() |
±---------+
| 97841443 |
±---------+
1 row in set (6.30 sec)
analyze相关配置
mysql> show variables like ‘%analyze%’;
±---------------------------------------±------------+
| Variable_name | Value |
±---------------------------------------±------------+
| tidb_analyze_partition_concurrency | 1 |
| tidb_analyze_version | 2 |
| tidb_auto_analyze_end_time | 23:59 +0000 |
| tidb_auto_analyze_partition_batch_size | 1 |
| tidb_auto_analyze_ratio | 0.5 |
| tidb_auto_analyze_start_time | 00:00 +0000 |
| tidb_enable_analyze_snapshot | OFF |
| tidb_enable_auto_analyze | ON |
| tidb_enable_fast_analyze | OFF |
| tidb_max_auto_analyze_time | 43200 |
| tidb_mem_quota_analyze | -1 |
| tidb_persist_analyze_options | ON |
±---------------------------------------±------------+
请教是什么原因呢