0

我有以下三个用于消息传递系统的表:

`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。(我的三点中的第一点)。我将如何构建整个查询?

4

2 回答 2

1

您可以使用相关子查询来获取特定线程的最新消息。尝试这个:

SELECT 
    a.id, 
    b.content, 
    b.timestamp
FROM
    messaging_messagethread a
INNER JOIN
    messaging_message b ON a.id = b.thread_id 
WHERE 
    b.timestamp = 
    (
        SELECT MAX(timestamp) 
        FROM messaging_message 
        WHERE thread_id = a.id
    )
    AND b.id NOT IN
    (
        SELECT message_id
        FROM messaging_messagestatus
        WHERE status = 'deleted'
    )
    AND 4 IN (a.initiator_id, a.recipient_id)
ORDER BY
    b.timestamp DESC

如果我理解正确,我相信这就是你想要的。

于 2012-06-10T00:08:20.667 回答
0

问题是您想要来自每个线程的最新消息,不幸的是,无法通过组 AFAIK 检索顶级成员所以我所做的基本上是从用户相关的每个 thread_id 获取所有消息,然后简单地返回顶部id ...哦,并检查该消息没有被删除。我不确定这是否正确。

但请重新考虑一种不同的方法,可能使用一种编程语言或多个查询。因为这会很慢......

SELECT thread_id, content, timestamp
FROM messaging_message
WHERE messaging_message.id IN
(
    SELECT messaging_message.id
    FROM messaging_message
        INNER JOIN messaging_messagestatus ON
            (messaging_messagestatus.message_id = messaging_message.id)
    WHERE messaging_message.thread_id IN
            (SELECT DISTINCT id 
             FROM messaging_messagethread
             WHERE initiator_id = 4 OR recipient_id = 4) AND
         messaging_messagestatus.status != 'deleted'
     ORDER BY timestamp DESC
     LIMIT 1
)
ORDER BY timestamp DESC

祝你好运。

于 2012-06-09T06:08:36.317 回答