如何优化此查询?查询速度慢

时间:2018-07-04 13:36:16

标签: mysql database database-optimization

嗨,我正在尝试优化此查询。 如果在该时间范围内有很多事务,则可能需要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

2 个答案:

答案 0 :(得分:2)

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

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已经断言了
  • 删除了反引号,因为我不喜欢它们

答案 1 :(得分:-1)

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

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`