【发布时间】:2022-10-01 12:04:20
【问题描述】:
嗯,我刚到一个项目,对SQL调优不太了解。
我看到了一个需要很长时间才能运行的进程,我开始查看这个进程执行的一些查询。
其中一个查询是运行最多需要 10 分钟的连接计数。
select count(rtvp.id) from rel_transaction_voucher_product rtvp
join `transaction` t on t.id = rtvp.transaction_id
join voucher v on v.id = rtvp.voucher_id
where v.situation_code = \'YYYYY\'
and t.transaction_type_code = \'XXXX\'
and t.expiration_date < curdate()
查询中每个表的行:
- rel_transaction_voucher_product:170 万
- 交易:160万
- 代金券:130万
解释结果:
id|select_type|table|partitions|type |possible_keys |key |key_len|ref |rows |filtered|Extra |
--+-----------+-----+----------+------+--------------------------------------------------------------------------------------------+--------------------------------------------------+-------+--------------------------+------+--------+-----------+
1|SIMPLE |t | |ref |PRIMARY,transaction_type_code,transaction_id_type_date_IDX |transaction_type_code |38 |const |815765| 33.33|Using where|
1|SIMPLE |rtvp | |ref |uk_transid_voucherid_productid,voucher_id,rel_transaction_voucher_product_transaction_id_IDX|rel_transaction_voucher_product_transaction_id_IDX|38 |voucherprd.t.id | 1| 100.0| |
1|SIMPLE |v | |eq_ref|PRIMARY,fk_voucher_situation_code |PRIMARY |38 |voucherprd.rtvp.voucher_id| 1| 45.46|Using where|
我意识到如果我删除and t.expiration_date < curdate(),查询会在大约 30 秒内返回,但这个条件非常重要。
反正有没有让这个查询运行得更快?
-
尝试在
(transaction_type_code, expiration_date)上添加索引 -
@Barmar。 . .哇!它显着提高了性能,运行大约需要 3 - 5 秒。天才!太感谢了。