如何使用1,2和2,1两者组

时间:2016-07-11 10:24:20

标签: mysql

我的查询

select id,user_id,friend_id 
from message 
where user_id = '$user_id' 
or friend_id = '$user_id' 
group by user_id,friend_id;

但我有多个记录,例如1,61和61,1用户。我想要一个记录,但两个用户要么发送或收到消息。是否可以通过user_id,friend_id和friend_id,user_id

设置组

2 个答案:

答案 0 :(得分:3)

您可以使用CASE EXPRESSION

SELECT t.id,
       CASE WHEN t.user_id > t.friend_id THEN t.user_ID ELSE t.friend_ID end as ID_1,
       CASE WHEN t.user_id > t.friend_id THEN t.friend_id ELSE t.user_id end as ID_2
FROM message t 
where t.user_id = '$user_id' or
 t.friend_id = '$user_id' 
group by ID_1,ID_2

答案 1 :(得分:1)

如果您想获得与61通信的所有用户的列表:

SELECT (CASE WHEN user_id = 61 THEN friend_id ELSE user_id END) AS usr
FROM message 
WHERE user_id = 61 OR friend_id = 61 
GROUP BY usr

SQLFiddle:http://sqlfiddle.com/#!15/2197d/12/0