我有一个与 ORDER BY
或 GROUP BY
子句相关的问题。
例如我有以下查询
SELECT country_name,COUNT(*) FROM user_location
WHERE country_name IS NOT NULL
GROUP BY country_name
ORDER BY COUNT(*) DESC
和
SELECT country_name,COUNT(*) As Total FROM user_location
WHERE country_name IS NOT NULL
GROUP BY country_name
ORDER BY Total DESC
在第二个查询中,我在 ORDER BY
子句中为 COUNT(*)
使用别名 Total
。
两个查询是否存在任何与性能相关的差异?
最佳答案
我在一张表上运行了以下测试,该表包含与 10K 个类别随机相关的 100 万个产品 (MariaDB 10.0.19):
select p.categoryId, count(*) as total
from products p
group by p.categoryId
having count(*) = 100
执行时间:156 毫秒
select p.categoryId, count(*) as total
from products p
group by p.categoryId
having total = 100
执行时间:156 毫秒
因此在性能上似乎没有任何差异。
请注意,使用 ORDER BY
时,引擎会将结果复制到临时表中(参见 EXPLAIN:Using temporary;Using filesort
)。因此,即使您使用 ORDER BY COUNT(*)
,也无法重新计算该值。
但是 - 当我使用 ORDER BY COUNT(DISTINGT ...)
时存在差异(我无法解释):
select p.categoryId, count(distinct p.productData) as total
from products p
group by p.categoryId
order by total
配置文件:复制到 tmp 表
需要 863 毫秒
select p.categoryId, count(distinct p.productData) as total
from products p
group by p.categoryId
order by count(distinct p.productData)
配置文件:复制到 tmp 表
需要 963 毫秒
关于mysql - 在 ORDER BY 子句和聚合函数别名中使用聚合函数是否存在与性能相关的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45636306/