有一张聊天表,我在其中收集了 user_from
、user_to
和示例中其他不重要的内容。
想要获取对话中所有相关用户的 user_id(使用当前 user_id 的 where 子句)。
在下面的示例中,我试图搜索存在 user_id=1
的所有用户,但我知道这行不通,也不知道如何让它发挥作用。
SELECT *
FROM messages M
WHERE M.user_from="1" OR M.user_to="1"
GROUP by m.user_from, m.user_to
如果表中有行(下)。其实我最后想收到数组([0]=>2,[1]=>4),因为user_id=1只与user_id=2和user_id=4对话
user_from | user_to
1 2
1 2
2 1
1 4
3 2
可能我必须在 Select 中使用 Select 或使用任何类型的 Case When Then,但不知道如何正确循环它
已解决按最后 MSG_ID 订购!!!
SELECT (IF( user_from = 1, user_to, user_from )) as user_id
FROM messages
WHERE `user_from` = 1 OR `user_to` = 1
GROUP BY user_id
ORDER BY MAX(msg_id) DESC
最佳答案
select user_to as user_id
from messages
where user_from = 1
union
(select user_from as user_id
from messages
where user_to = 1)
根据@Анжел Миленов 的建议进行编辑 - (我个人不知道为什么括号在 mySql 中会有所不同)
关于mysql - 必须使用什么 SQL 语句从 1 个表但 2 个列中获取非重复 ID 的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27190798/