我该怎么做这个SQL查询?

时间:2011-10-05 22:06:03

标签: php mysql sql

我有一些消息和当前用户。

消息有id,用户有id

我想获得一个(唯一的)用户ID列表,其中包含:

第一个用户id适用于向最高消息id的当前用户发送消息的用户 并且最后一个用户ID的所有消息ID都低于向当前用户发送消息的任何其他用户的消息ID。

到目前为止,我能够获得向当前用户发送消息的用户列表:

"SELECT sender_id AS messgr_id FROM   messages 
    WHERE  receiver_id = '$curr_id' 
UNION SELECT receiver_id AS messgr_id FROM messages
    WHERE  sender_id = '$curr_id' ";

但我坚持按照我想要的方式订购它的最佳方式(我正在学习SQL,因为我这样做,所以我不是专家:))

谢谢!

2 个答案:

答案 0 :(得分:2)

这样的事情应该可以解决问题

SELECT * 
FROM ( 
    SELECT sender_id AS messgr_id FROM   messages 
        WHERE  receiver_id = '$curr_id' 
    UNION SELECT receiver_id AS messgr_id FROM messages
        WHERE  sender_id = '$curr_id'
) T1
GROUP BY messgr_id
ORDER BY messgr_id DESC

这将为您提供用户ID 的列表,其中删除了重复项,并从高到低排序。


<强>更新

重新阅读您的问题,听起来您正在查找按消息 ID排序的用户ID列表 - 当前未在您的示例中显示。假设您的messages表格中包含id列(除了receiver_idsender_id),请按以下步骤操作:

SELECT messgr_id, max(message_id) as max_message_id
FROM ( 
    SELECT sender_id AS messgr_id, id as message_id FROM messages 
        WHERE  receiver_id = '$curr_id' 
    UNION SELECT receiver_id AS messgr_id, id as message_id FROM messages
        WHERE  sender_id = '$curr_id'
) T1
GROUP BY messgr_id
ORDER BY max_message_id DESC

答案 1 :(得分:0)

我不确定,但我认为你只想订购你的SELECTion?

"SELECT sender_id AS messgr_id FROM   messages 
    WHERE  receiver_id = '$curr_id'
    ORDER BY sender_id
UNION SELECT receiver_id AS messgr_id FROM messages
    WHERE  sender_id = '$curr_id' 
    ORDER BY sender_id DESC";