mysql - 在 ORDER BY 子句和聚合函数别名中使用聚合函数是否存在与性能相关的差异?

标签 mysql aggregate-functions query-performance

我有一个与 ORDER BYGROUP 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/

相关文章:

php - 与此等效的 mysqli 是什么?

mysql - 加入 Max Row where Col

postgresql - 如何在 PostgreSQL sum() 中检测 NULL 行

MySql 与 SQL-Server 的性能问题

具有 2 个内部连接的 MySQL 慢查询

php - Laravel 数据库查询优化

mysql - 哪个更好 : has_one(single column table) or a string column?

MySQL在任何地方找到包含所有字母的单词

mysql - 按时间间隔聚合对查询结果进行分组

PostgreSQL citext 索引与较低的表达式索引性能