2011-03-08 64 views
0

UPDATE:补充说,运行查询第二最:从这个查询的MySQL索引中受益?

(考虑采取索引的时候,也许需要???)

SELECT m.time, m.message, m.receiver_uid AS receiver, m.sender_uid AS sender 
    FROM messages AS m, users AS u 
    WHERE u.uid = '$coID' 
     AND ((m.receiver_uid = '$meID' AND m.sender_uid = '$coID') OR 
       (m.receiver_uid = '$coID' AND m.sender_uid = '$meID')) 
    ORDER BY m.time DESC 
  • $ MEID是用户的ID,谁运行wuery,
  • $ coID是联系人的ID。

我有一个大一些查询,并将其每次运行一个用户访问我的网页。

SELECT m2.message, m2.time, m2.sender_uid AS sender, m2.receiver_uid AS receiver, 
     m.contact, u.ufirstname 
FROM ( SELECT CASE 
       WHEN sender_uid = '$me' THEN receiver_uid 
       ELSE sender_uid 
       END AS contact, 
       MAX(time) AS maxtime 
     FROM messages 
     WHERE sender_uid = '$me' OR receiver_uid = '$me' 
     GROUP BY CASE 
       WHEN sender_uid = '$me' THEN receiver_uid 
       ELSE sender_uid 
       END          ) AS m 
INNER JOIN messages m2 ON m.maxtime = m2.time 
AND ((m2.sender_uid = '$me' AND m2.receiver_uid = m.Contact) 
OR (m2.receiver_uid = '$me' AND m2.sender_uid = m.Contact)) 
INNER JOIN users AS u ON m.contact = u.uid 
ORDER BY time DESC 
  • $我是谁运行查询的用户的ID

这个查询(成功)检索:

LAST MESSAGE from EVERY 'CONVERSATION' ordered by TIME. 

所以它会得到的最后消息(在每个PM会话中是否发送或接收消息) 然后按时间排序并检索联系人信息。

请告诉我,如果我没有正确解释它。

我的MySQL表看起来是这样的:从什么指数(ES)将这个查询利益

receiver_id | sender_id | message | time 

(用户表已有的ID的主键,以便在加入部分检索联系人的名称应该是有效的)

EXPLAIN输出:

大查询:

id select_type  table type possible_keys key  key_len  ref  rows Extra 
1 PRIMARY  <derived2> ALL  NULL NULL NULL NULL 4 Using temporary; Using filesort 
1 PRIMARY  m2 ALL  NULL NULL NULL NULL 42 Using where 
1 PRIMARY  u eq_ref PRIMARY  PRIMARY  4 m.contact 1 Using where 
2 DERIVED  messages ALL  NULL NULL NULL NULL 42 Using where; Using temporary; Using filesort 

在更新部分查询:

id select_type  table type possible_keys key  key_len  ref  rows Extra 
1 SIMPLE u const PRIMARY  PRIMARY  4 const 1 Using index; Using filesort 
1 SIMPLE m ALL  NULL NULL NULL NULL 42 Using where 

回答

0

我发现通过跟踪和错误,索引时间减少了加载时间。 所以这可能是我的问题的答案。

0

随着消息表的增长,此查询将开始变得越来越慢。根据用户参与的对话数量,您将开始看到呈指数衰减的性能。尽管messages.time,messages.sender_uid和messages.receiver_uid上的单独索引目前会有所帮助,但是除非您修改了邮件表,否则索引将从长远角度帮助您。特别是当你有超过几十万条消息。

我建议维护一个关联类型类型,将用户链接到对话和他们的最后一个消息ID。东西看起来像:

user_id | conversation_id | message_id

然后查找此表,而不是执行复杂且昂贵的查询。这大大减少了您在消息表上需要执行的扫描次数。虽然它稍微增加了复杂性,但性能不会像上面的查询那样降级。

+0

如何将旧的(14天)消息移动到较旧的表中? 所以,只有当用户真的想阅读旧信息时,他必须在长表中搜索。 – SuperSpy 2011-03-08 11:25:44