Mysql Order By after Group By 导致查询非常慢

标签 mysql group-by sql-order-by

我不明白为什么下面 Query2 中的“order by”子句会导致它占用一分钟多的时间,而第一个子句会立即返回结果。有没有更好的方法来执行此“排序方式”

快速:

select c.id, max(date(a.sent)) as sent,
    if(c.id in (select id from bin where (num=1 or  num=2)),1,0) as done
from test c, test2 a
where c.id=a.id
group by c.id
limit 1;

select c.id, max(date(a.sent)) as sent,
    if(c.id in (select id from bin where (num=1 or num=2)),1,0) as done
from test c, test2 a
where c.id=a.id
group by c.id
order by done, sent
limit 1;

最佳答案

这是因为order by子句中的“列”并不是真正的列,而是查询中别处计算的别名。因此,它们没有被编入索引,服务器必须即时对它们进行排序。使用连接来计算完成,而不是子查询,可能会大大加快速度。

关于Mysql Order By after Group By 导致查询非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20005235/

相关文章:

mysql - 来自备份脚本的错误查询导致错误 1064

MySql 获取默认或最小行的值

MySQL:按多列分组未给出准确的结果

sql - 我可以在 SQL 中执行 max(count(*)) 吗?

mysql - 需要在 mysql 中进行排序的帮助

mysql - 从两个表中选择返回空值

mysql - 创建表失败,即使我检查了语法错误

r - 根据前 5 个值汇总 R 中的多列

python - 按 Pandas 数据框分组并在每组中选择最新的

php - MySQL ORDER BY 优化多个连接