我不明白为什么下面 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/