在消息数据库表中获取不同的用户

时间:2011-08-29 03:30:59

标签: php mysql sql

对于具有以下结构的messages

id, sender_id, receiver_id, text

我想构建一个不同用户的列表(按消息ID排序),他们向当前会话持有者发送消息或从当前会话持有者那里收到消息。该列表应仅包含一次用户。

查询如:

"SELECT * FROM messages WHERE sender_id = '$sess_id' OR receiver_id = '$sess_id'";

产生重复,即具有相同用户的多行。是否必须在SQL查询之后进行过滤,或者是否存在将产生所需唯一列表的SQL查询?

谢谢!

3 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT sender_id
FROM   messages
WHERE  receiver_id = '$sess_id'
UNION
SELECT receiver_id
FROM   messages
WHERE  sender_id = '$sess_id'

答案 1 :(得分:0)

您还可以使用distinct关键字:

SELECT distinct sender_id
FROM   messages
WHERE  receiver_id = '$sess_id'
UNION
SELECT distinct receiver_id
FROM   messages
WHERE  sender_id = '$sess_id'

可在此处找到更多信息:

http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html

答案 2 :(得分:0)

SELECT
  CASE receiver_id WHEN '$sess_id' THEN sender_id ELSE receiver_id END AS user_id
FROM messages
WHERE receiver_id = '$sess_id'
   OR sender_id = '$sess_id'
GROUP BY CASE receiver_id WHEN '$sess_id' THEN sender_id ELSE receiver_id END
ORDER BY MAX(message_id)

MySQL允许您在GROUP BY子句中引用列别名,因此您也可以执行以下操作:

…
GROUP BY user_id
…