mysql - 如何优化这个查询?慢查询

标签 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

最佳答案

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

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

关于mysql - 如何优化这个查询?慢查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51175034/

相关文章:

mysql - 如何使用另一个表中的数据更新sql中的表?

mysql - 如何删除mysql查询中的所有特殊字符

c# - Dapper MySQL 返回值

javascript - 使用 jQuery 序列化和 CodeIgniter 函数

database - postgresql 在数据库之间快速传输表

sql - 是否需要为包含数字的数据库列编制索引?

php - 如何在mysql中添加所有列的数据

mysql 从连接记录中获取总行数

database - 为什么我不能访问具有 ACL 上的管理员访问权限的 Notes 数据库?

c++ - 是否推荐使用 PRAGMA synchronous=OFF 来提高性能