使用线程和消息构建收件箱查询

时间:2012-08-16 15:53:05

标签: mysql

所以我有两个表来处理消息threadsmessages

messages:
id | thread | user_from | user_to | text | created

threads:
id | user_from | user_to | created | status

我想构建一个查询,用以获取线程:

  1. 该主题的最新消息
  2. 该线程的ID
  3. 到目前为止,我一直在处理这个问题,首先获取所有线程(当然有适当的限制),然后分别获取每个线程的最新消息。

    有什么想法吗?

    更新:

    表格关系:messagesthread = threadsid

3 个答案:

答案 0 :(得分:1)

select t.id, max(m.id) as last_message_id
from threads t
left outer join messages m on m.thread = t.id
group by t.id

答案 1 :(得分:1)

脱离我的头顶:

SELECT t.id, m.* FROM threads t
INNER JOIN messages m ON m.thread = t.id
WHERE m.id = 
   (SELECT id FROM messages WHERE thread = t.id ORDER BY id DESC LIMIT 1);

[edit]经过测试,似乎工作正常。

答案 2 :(得分:1)

尝试这个

SELECT  a.id     AS ThreadID, 
        c.`text` AS LatestMessage
FROM    threads a 
            INNER JOIN
            (
                SELECT  thread, max(created) maxCreated
                FROM    messages
                GROUP BY thread
            ) b on a.id = b.thread 
            INNER JOIN messages c
                    on a.id = c.thread AND
                       b.maxCreated = c.created