这是查询:
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
表的DESCRIBE。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
子句中使用函数不是一个好习惯,因为不能使用索引。...查询在执行EXPLAIN时会抛出“使用临时”和“使用文件排序”。
从我的found来看,使用DISTINCT / GROUP BY时可以预料到的。
关于sql - 如何优化此SQL查询以摆脱文件排序和临时表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1695541/