构建SQL查询以连接三个表以获取消息传递信息

时间:2012-06-09 04:00:28

标签: mysql sql

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

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

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分: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
祝你好运。