mysql“group by”查询非常慢

时间:2010-10-26 16:23:02

标签: sql mysql sql-optimization

我在一个有大约100k记录的表中有这个查询,它运行得很慢(3-4s),当我取出组时它更快(少于0.5s)。我很想知道如何解决这个问题:

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_ididsenderidrecipientid

解释退货:

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

任何想法如何在返回相同结果时加快速度(每个线程有多条消息,我想在此查询中每个线程只返回一条消息)。

提前感谢。

2 个答案:

答案 0 :(得分:1)

试试这个:

select m.thread_id, m.id, m.senderid, m.recipientid, 
       f.username as from_name, t.username as to_name
from msgtable m
join usertable f on m.senderid = f.id
join usertable t on m.recipientid = t.id
where m.id = (select MAX(id) from msgtable where thread_id = m.thread_id)

或者这个:

select m.thread_id, m.id, m.senderid, m.recipientid, 
       (select username from usertable where id = m.senderid) as from_name,
       (select username from usertable where id = m.recipientid) as to_name
from msgtable m
where m.id = (select MAX(id) from msgtable where thread_id = m.thread_id)

为什么用户表会加入?消息是否可以丢失或来自?..

答案 1 :(得分:0)

最大的问题是msgtable上没有可用的索引。在至少 senderidrecipientid上创建索引,它应该有助于提高查询速度,因为它会限制需要扫描的结果数量。