在Group By之后的Mysql Order By导致非常慢的查询

时间:2013-11-15 16:00:36

标签: mysql group-by sql-order-by

我无法弄清楚'为什么要按顺序排列'下面的Query2中的子句导致它占用一分钟,而第一个子句立即返回结果。是否有更好的方法来执行此操作'按顺序排列

快速:

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;

2 个答案:

答案 0 :(得分:1)

这是因为order by子句中的“columns”不是真正的列,而是查询中其他位置的计算的别名。因此,它们没有编入索引,服务器必须在运行中对它们进行排序。使用连接来计算已完成而不是子查询,可能会加快这一速度。

答案 1 :(得分:0)

如果要恢复所有记录,则排序不应花费太多时间,即使它们是计算/非索引字段。但是,您使用的是“限制1”。这改变了优化器的方法。

在第一种情况下,您按ID排序。由于您具有“限制1”并且ID可能具有索引,因此优化程序可以通过ID获取ID,并且当它获得与WHERE子句匹配的一条记录时,它可以返回。

但是,在第二个查询中,即使您只想要1个记录,优化器也不会知道哪个记录将被计算,除非它计算整个集合(就好像您没有“限制1”)然后只返回第一个。

取下“LIMIT 1”并比较两个查询。如果差异仍然存在,则可能是另一个问题。

很难说什么最适合您的音量。试试这个问题:

select id, max(date(sent)) as sent, 0 As done
from test2
where exists (select 1 from bin where bin.id=test2.id and num not in (1,2))
group by id
union all
select id, max(date(sent)) as sent, 1 As done
from test2
where exists (select 1 from bin where bin.id=test2.id and num in (1,2))
group by id
order by done, sent
limit 1

SQL Fiddle is here如果你想调整它。

我遗漏了测试表,因为你没有带回除ID之外的任何字段,这已经在test2上了。如果你需要测试的其他字段,你将不得不调整它。

相关问题