1

我正在尝试将对话中的消息分组,以便可以将它们作为对话阅读。

这就是我现在所拥有的

桌子messages

id | from | to | message | timestamp  
1  | 1    | 2  | 'Hello' | 1351257766
2  | 1    | 3  | 'Hey!'  | 1351257767
3  | 2    | 1  | 'Hay!'  | 1351257768

messages.fromandmessages.to字段对应于users表中的一行。

我想要做的是:(不在同一个查询中)

一种。获取来自用户的所有对话的最后一条消息的列表(因此其中一个fromto等于给定的user.id
b. 获取属于一个对话的所有消息。

SELECT
-- From-user:
    users_from.id               AS from_id,
    users_from.username         AS from_username,
    users_from.nickname         AS from_nickname,
    users_from.username_safe    AS from_username_safe,
    users_from.password         AS from_password,
    users_from.email            AS from_email,
    users_from.rank             AS from_rank,
    users_from.email            AS from_email,
    users_from.ip               AS from_ip,
    users_from.last_online      AS from_last_online,
    users_from.register_stamp   AS from_register_stamp,
    users_from.state            AS from_state,
    users_from.icon             AS from_icon,

-- To-user:
    users_to.id                 AS to_id,
    users_to.username           AS to_username,
    users_to.nickname           AS to_nickname,
    users_to.username_safe      AS to_username_safe,
    users_to.password           AS to_password,
    users_to.email              AS to_email,
    users_to.rank               AS to_rank,
    users_to.email              AS to_email,
    users_to.ip                 AS to_ip,
    users_to.last_online        AS to_last_online,
    users_to.register_stamp     AS to_register_stamp,
    users_to.state              AS to_state,
    users_to.icon               AS to_icon,

-- Messages:
    messages.id,
    messages.from,
    messages.to,
    messages.message,
    messages.timestamp


FROM messages

-- Some joins to get the userdata
INNER JOIN users AS users_to
    ON messages.to = users_to.id
INNER JOIN users AS users_from
    ON messages.from = users_from.id

-- We only want the latest messages:
RIGHT JOIN (
    SELECT
        max(messages.id) AS maxid,
        messages.from,
        messages.to
    FROM messages
    WHERE messages.to = {userid} OR messages.from = {userid}
) limiter
    ON messages.id = limiter.maxid

这是我现在正在使用的,但它不起作用。它只返回其中一个对话。

我希望你们能帮助我完成这项工作!

更新: 给出的答案不起作用。当用户 1 向用户 2 发送消息时,它起作用了。但是,当用户 2 回复时,它开始了单独的对话(作为结果中的新行)。

4

1 回答 1

2

您的查询很接近,但我认为您也需要按用户分组。这是一种方法

RIGHT JOIN (
    SELECT
        max(messages.id) AS maxid,
        messages.from,
        messages.to
    FROM messages
    WHERE messages.to = {userid} OR messages.from = {userid}
    group by messages.from, messages.to
) limiter

您对对话的定义似乎具有相同的两个用户。为此,请使用in

select m.*
from messages m
where `from` in ({userid1}, {userid2}) and
      `to` in ({userid1}, {userid2})

顺便说一句,from并且to是错误的列名,因为from是保留字。

于 2013-02-10T16:40:44.277 回答