0

桌子:

+----+----------+-----------+---------+
| id | topic_id | from_user | to_user |
+----+----------+-----------+---------+
|  6 |        5 | 4         | 5       |
|  2 |        6 | 5         | 2       |
|  3 |        5 | 2         | 5       |
|  4 |        4 | 5         | 4       |
|  5 |        4 | 5         | 4       |
|  7 |        6 | 5         | 2       |
|  8 |        5 | 2         | 5       |
|  9 |        5 | 4         | 5       |
| 10 |        0 | 2         | 5       |
| 11 |        6 | 5         | 2       |
| 12 |        3 | 5         | 2       |
| 13 |        0 | 5         | 2       |
+----+----------+-----------+---------+

这是消息表(类似于私人消息),from_user 和 to_user 是自我描述的,topic_id 对此并不重要

现在,我需要选择将在当前登录用户的收件箱中显示的消息列表。我将使用会话变量引用此用户$this_user = $_SESSION['id']

我有这个查询:

SELECT * 
FROM messages 
WHERE from_user = '$this_user' OR 
      to_user = '$this_user' 

但这将需要重复消息,例如 4 - 5、5 - 4、5 - 4、

我尝试使用 DISTINCT 但也不起作用

任何帮助

4

4 回答 4

2

不确定您如何使用 DISTINCT(显示查询),但或者这也应该有效:

SELECT * FROM messages 
   WHERE from_user = '$this_user' OR to_user = '$this_user'
   GROUP BY `id`
于 2012-11-08T15:06:52.260 回答
2

采用UNION ALL

SELECT 'From You' type, * FROM messages m WHERE from_user = '$this_user'
UNION ALL
SELECT 'To You', * FROM messages m WHERE to_user = '$this_user'

SQL 小提琴演示

于 2012-11-08T15:07:16.800 回答
2

试试这个,

select least(from_user, to_user) as x, greatest(from_user, to_user) as y
from   tableName
WHERE  from_user = '$this_user' OR to_user = '$this_user'
group by x, y
于 2012-11-08T15:09:33.580 回答
1

您肯定需要在topic_id列上使用分组吗?使用这样的查询:

SELECT * FROM messages
WHERE from_user = '$this_user' OR to_user = '$this_user'
GROUP BY `topic_id`

给我我相信你正在寻找的结果。有关示例,请参阅此SQLFiddle

于 2012-11-08T15:23:41.443 回答