这是查询:
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
在WHERE
、GROUP BY
和ORDER 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/