sql - 我如何优化此 SQL 查询以摆脱文件排序和临时表?

标签 sql mysql database refactoring

这是查询:

SELECT 
  count(id) AS count 
FROM `numbers` 
GROUP BY 
  MONTH(created_at), 
  YEAR(created_at) 
ORDER BY 
  YEAR(created_at), 
  MONTH(created_at)

该查询在执行 EXPLAIN 时抛出“使用临时”和“使用文件排序”。

最终我要做的是查看用户提交的跟踪编号表并计算提交的行数并按月/年对计数进行分组。

即。 2008 年 11 月,提交了 11,312 行。

更新,这是numbers 表的描述。

id  int(11) NO  PRI NULL    auto_increment
tracking    varchar(255)    YES     NULL    
service varchar(255)    YES     NULL    
notes   text    YES     NULL    
user_id int(11) YES     NULL    
active  tinyint(1)  YES     1   
deleted tinyint(1)  YES     0   
feed    text    YES     NULL    
status  varchar(255)    YES     NULL    
created_at  datetime    YES     NULL    
updated_at  datetime    YES     NULL    
scheduled_delivery  date    YES     NULL    
carrier_service varchar(255)    YES     NULL    

最佳答案

试一试:

  SELECT COUNT(x.id)
    FROM (SELECT t.id,
                 MONTH(t.created_at) 'created_month', 
                 YEAR(t.created_at) 'created_year'
            FROM NUMBERS t) x
GROUP BY x.created_month, x.created_year
ORDER BY x.created_month, x.created_year

WHEREGROUP BYORDER BY 子句中使用函数不是一个好习惯,因为不能使用索引。

...query throws a 'Using temporary' and 'Using filesort' when doing EXPLAIN.

来 self found ,这在使用 DISTINCT/GROUP BY 时是可以预期的。

关于sql - 我如何优化此 SQL 查询以摆脱文件排序和临时表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1695541/

相关文章:

mysql - SQL - 行具有最新日期的分组依据

mysql查询 - 计算相似的术语

php - 仅在 mysql 数据库中插入一次。

带有字符串列的 SQL Between 子句

sql - 具有序列的 Multi-Tenancy 系统(在 Azure 上)

具有顺序和限制的MySQL查询

java - 如何使用ibatis获取sql count查询的输出?

mysql group by with having

mysql - 表与 SQL 请求冲突

java - 使用java将数据从数据库设置到Extjs网格