繁体   English   中英

MySQL 上的慢速计数(带连接)查询

[英]Slow count (with join) query on MySQL

额,刚到项目,对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 秒内返回,但这个条件非常重要。

无论如何让这个查询运行得更快?

WHERE条件中使用的列上添加索引。

ALTER TABLE transaction ADD INDEX (transaction_type_code, expiration_date);

如果您已经在transaction_type_code上有一个索引,您将不再需要它,因为它是这个新索引的前缀。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM