我有以下三个用于消息传递系统的表:
`messaging_messagethread`
- id
- subject
- initiator_id # who creates the thread
- recipient_id
`messaging_message`
- id
- thread_id
- content
- timestamp
- sender_id
`messaging_messagestatus` # a status will be created for each recipient of a message
- id
- message_id
- recipient_id
- status
给定一个用户,我需要构建一个查询来获得以下信息:
- 显示线程 ID(不同),
content
以及timestamp
该线程中的最新消息- 删除带有最新消息的所有线程
status='deleted'
。
这是我到目前为止所拥有的:
SELECT DISTINCT thread.id as thread_id, timestamp.timestamp
FROM messaging_messagethread thread
INNER JOIN
(SELECT thread_id, MAX(timestamp) as timestamp
FROM messaging_message GROUP BY thread_id) timestamp
ON thread.id = timestamp.thread_id
WHERE initiator_id = 4 OR thread.recipient_id = 4 ORDER BY timestamp.timestamp DESC
这给了我按最近时间戳排序的不同线程 ID。(我的三点中的第一点)。我将如何构建整个查询?