我有一个类似
的mysql表聊天+---------+-----------+-------------+----------------+
| chat_id | sender_id | receiver_id | msg |
+---------+-----------+-------------+----------------+
| 1 | 1002 | 1001 | test |
| 2 | 1001 | 1002 | test |
| 3 | 1002 | 1001 | test |
| 5 | 1001 | 1002 | asdf |
| 6 | 1003 | 1001 | tesdf |
| 9 | 1001 | 1003 | tasdfa a fasd |
| 10 | 1001 | 1004 | dsf asdf a |
| 11 | 1005 | 1001 | dsf asdf asdf |
+---------+-----------+-------------+----------------+
用户1002,1003,1004,1005中存在用户1001的会话
我需要用户1001进行对话的用户列表(1002,1003,1004,1005)。
mysql查询是什么?请帮帮我。
答案 0 :(得分:5)
您可以在sender
或receiver
中选择要搜索的特定用户的所有记录。在该测试之后,如果发送者的id等于您要搜索的用户ID,如果它是相等的,则返回接收者的id,否则返回发送者。提供DISTINCT
关键字仅显示结果列表中的唯一ID。
SELECT DISTINCT
CASE WHEN sender_id = 1001
THEN receiver_id
ELSE sender_id
END userID
FROM tableName
WHERE 1001 IN (sender_id, receiver_id)
因为你想连接行based on your comment
SELECT GROUP_CONCAT(DISTINCT
CASE WHEN sender_id = 1001
THEN receiver_id
ELSE sender_id
END) userID
FROM tableName
WHERE 1001 IN (sender_id, receiver_id)
答案 1 :(得分:3)
试试这个
select DISTINCT if(receiver_id='1001',sender_id,receiver_id) AS id
from YourTable
where (sender_id = 1001 OR receiver_id = 1001)
编辑:
SELECT GROUP_CONCAT( DISTINCT (
if( receiver_id = '1001', sender_id, receiver_id ) )
) AS concat
FROM chat
WHERE (
sender_id =1001
OR receiver_id =1001
)
我认为您了解GROUP_CONCAT尺寸问题。您可以参考此http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
答案 2 :(得分:1)
您可以使用union
合并发件人或收件人为1001的两个查询:
select distinct sender_id
from YourTable
where receiver_id = 1001
union
select distinct receiver_id
from YourTable
where sender_id = 1001
答案 3 :(得分:0)
HI请检查以下查询
从表中选择不同的receiver_id,其中distinct sender_id = 1001
答案 4 :(得分:0)
(select distinct receiver_id from table where sender_id = 1001)
union distinct
(select distinct sender_id from table where receiver_id = 1001);