0

实际上,我正在尝试创建一个像 FB(Messages) 这样的对话界面,并为此使用 sql 查询来获取所有与用户交谈过的人。我需要他按降序交谈的用户的 id,比如如果 A 与 B 和 C 聊天。那么 B AND C 将是该查询的结果,B 将排在第一位,因为 A 最近与 B 聊天。

我的“消息”表结构是: http: //www.softnuke.com/me/files/DB.png

这是 FB 示例: http: //www.softnuke.com/me/files/msg.png

这是我的错误查询,需要修复:

SELECT DISTINCT(`mates`)FROM(
    SELECT `time` AS `time`,`from_id` AS `mates` 
     FROM `messages` AS T WHERE (`from_id`=$uid OR `to_id`=$uid) 

    UNION

    SELECT `time` AS `time`,`to_id` AS `mates`
    FROM `messages` AS T WHERE (`from_id`=$uid OR `to_id`=$uid) 

    ) AS T 
    WHERE `mates`!='$uid'
    ORDER BY `time`

$uid 会给我我想要获取列表的用户变量(这里是它的 A)。

4

1 回答 1

0

您似乎正在了解主要人物和他们正在与之交谈的人,无论哪个是主要人物。也不太确定当您使用 DISTINCT 时 MySQL 将如何计算出订购时间,这将删除一些记录及其时间。

您可以通过以下方式获得最大时间和订单:-

SELECT `mates`, MAX(`time`) AS LatestConv
FROM(
    SELECT `time` AS `time`,`from_id` AS `mates` 
     FROM `messages` AS T WHERE `to_id`=$uid

    UNION

    SELECT `time` AS `time`,`to_id` AS `mates`
    FROM `messages` AS T WHERE `from_id`=$uid 

    ) AS T 
GROUP BY `mates`
ORDER BY LatestConv

要获取最新消息的状态:-

SELECT a.mates, a.LatestConv, IFNULL(b.Status, c.Status)
FROM
(
    SELECT mates, MAX(`time`) AS LatestConv
    FROM(
        SELECT `time` AS `time`, from_id AS mates 
        FROM messages AS T 
        WHERE to_id = $uid
        UNION
        SELECT `time` AS `time`, to_id AS mates
        FROM messages AS T 
        WHERE from_id = $uid 
        ) AS T 
    GROUP BY `mates`
) a
LEFT OUTER JOIN messages b
ON a.mates = b.from_id AND a.LatestConv = b.`time` AND b.to_id = $uid
LEFT OUTER JOIN messages c
ON a.mates = c.to_id AND a.LatestConv = c.`time` AND c.from_id = $uid
ORDER BY LatestConv

请注意,如果有多条消息发给同一个人且都共享相同的最新时间,这可能会让人感到困惑。如果这很可能,它可以处理如下: -

SELECT a.mates, a.LatestConv, MAX(IFNULL(b.Status, c.Status))
FROM
(
    SELECT mates, MAX(`time`) AS LatestConv
    FROM(
        SELECT `time` AS `time`, from_id AS mates 
        FROM messages AS T 
        WHERE to_id = $uid
        UNION
        SELECT `time` AS `time`, to_id AS mates
        FROM messages AS T 
        WHERE from_id = $uid 
        ) AS T 
    GROUP BY `mates`
) a
LEFT OUTER JOIN messages b
ON a.mates = b.from_id AND a.LatestConv = b.`time` AND b.to_id = $uid
LEFT OUTER JOIN messages c
ON a.mates = c.to_id AND a.LatestConv = c.`time` AND c.from_id = $uid
GROUP BY a.mates, a.LatestConv
ORDER BY LatestConv
于 2013-07-22T15:28:00.477 回答