需要正确的SQL查询

时间:2012-11-08 15:04:17

标签: php mysql sql

表:

+----+----------+-----------+---------+
| 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 个答案:

答案 0 :(得分:2)

不确定你是如何使用DISTINCT(显示查询),但也可以这样做:

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

答案 1 :(得分: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 fiddle Demo

答案 2 :(得分: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

答案 3 :(得分:1)

当然,您需要在topic_id列上使用分组? 使用这样的查询:

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

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