如何优化这个查询?慢速查询

ddrv8njm  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(539)

嗨,我正在尝试优化这个查询。如果在时间范围内有大量事务,则在本地环境中执行最多需要10秒。我试图在created_at列上创建一个索引,但是如果表中有很多行(我的表只有4m行),这个问题就解决不了了。有人能推荐一些优化技巧吗?

select 
   count(*) as total,
   trader_id 
from 
  (select * 
   from `transactions`
   where `created_at` >= '2018-05-04 10:54:00'
   order by `id` desc)
  as `transactions`
 where
   `transactions`.`market_item_id` = 1
    and `transactions`.`market_item_id` is not null
    and `gift` = 0
 group by `trader_id`;

编辑:

id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra

1   SIMPLE  transactions    NULL    range   transactions_market_item_id_foreign,transactions_trader_id_foreign,transactions_created_at_index    transactions_created_at_index   5   NULL    107666  2.41    Using index condition; Using where; Using MRR; Using temporary; Using filesort
gab6jxml

gab6jxml1#

删除(不必要的)内部查询:

select 
  count(*) as total,
  trader_id 
from transactions
where created_at >= '2018-05-04 10:54:00'
and market_item_id = 1
and gift = 0
group by trader_id

笔记:
删除了不必要的内部查询,增加了成本,大量增加了临时存储需求和使用量,并阻止任何索引使用其他条件
远离的 order by ,这将花费很多,但对结果没有影响
远离的 market_item_id is not null 条件,因为 market_item_id = 1 已经Assert
去掉背虱,因为我不喜欢它们

yftpprvb

yftpprvb2#

更好的波希米亚式查询版本在这里-

SELECT count(*) as total
      ,trader_id
FROM `transactions`
WHERE `created_at` >= '2018-05-04 10:54:00'
AND `market_item_id` = 1
AND `gift` = 0
GROUP BY `trader_id`

相关问题