我在一个有大约100k记录的表中有这个查询,它运行速度很慢(3-4s),当我取出这个组时速度更快(小于0.5s)。我很为亏损怎样做才能解决这个问题:mysql“group by”非常缓慢的查询
SELECT msg.id,
msg.thread_id,
msg.senderid,
msg.recipientid,
from_user.username AS from_name,
to_user.username AS to_name
FROM msgtable AS msg
LEFT JOIN usertable AS from_user ON msg.senderid = from_user.id
LEFT JOIN usertabe AS to_user ON msg.recipientid = to_user.id
GROUP BY msg.thread_id
ORDER BY msg.id desc
msgtable对thread_id
,id
,senderid
和recipientid
指标。
解释回报:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE msg ALL NULL NULL NULL NULL 162346 Using temporary; Using filesort
1 SIMPLE from_user eq_ref PRIMARY PRIMARY 4 db.msg.senderid 1
1 SIMPLE to_user eq_ref PRIMARY PRIMARY 4 db.msg.recipientid 1
任何想法如何,而返回相同的结果加快这(有每个线程多条消息,我想在此查询返回每个线程只有一个消息)。
在此先感谢。
'usertable'索引怎么样?你可以运行'EXPLAIN'并发布结果吗? –
Frankie
2010-10-26 16:25:21
通常,您必须在GROUP BY中声明SELECT中提到的所有未被聚合函数(COUNT,SUM,MIN,MAX等)封装的列。在这种情况下'DISTINCT'能更好地为您服务? – 2010-10-26 16:26:16
为什么左连接?每封邮件都不需要收件人和发件人吗? – 2010-10-26 16:29:43