mysql - 必须使用什么 SQL 语句从 1 个表但 2 个列中获取非重复 ID 的列表

标签 mysql sql

有一张聊天表,我在其中收集了 user_fromuser_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/

相关文章:

php - 每日页面比例MySQL查询

mysql - 在 AWS EC2 实例上将 MySQL 时区设置为 UTC

php - 在执行 SQL 文件时与 MySQL 一起使用 --ignore-table

sql - 错误,尝试插入时字符串或二进制数据将被截断

sql - 获取两个数字之间的偶数/奇数/所有数字

mysql - 通过连接另一个表从另一列中按 id 选择名称

php - 无法使用 CodeIgniter 插入数据库

mysql - 重复插入不保存

mysql - SQL Select SUM() 组函数使用无效

mysql - 3 Table JOIN - 有两个唯一的标识符从第三个中提取不同的数据