0

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

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

threads:
id | user_from | user_to | created | status

我想构建一个查询来获取我的线程:

  1. 该线程的最新消息
  2. 该线程的 id

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

有什么想法吗?

更新:

表关系:messagesthread= threadsid

4

3 回答 3

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
于 2012-08-16T15:55:43.590 回答
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);

[编辑] 经过测试,它似乎工作正常。

于 2012-08-16T15:58:59.410 回答
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
于 2012-08-16T16:03:02.247 回答