簡體   English   中英

使用線程和消息構建收件箱查詢

[英]building inbox query with threads and messages

所以我有兩個表來處理消息threadsmessages

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

threads:
id | user_from | user_to | created | status

我想建立一個查詢來獲取我的線程:

  1. 該線程的最新消息
  2. 該線程的ID

到目前為止,我一直在通過首先獲取所有線程(當然有適當的限制)然后分別獲取每個線程的最新消息來處理此問題。

有什么想法嗎?

更新:

表關系: messages thread = threads id

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

從我的頭頂上:

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);

[編輯]經過測試,似乎工作正常。

試試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM