我正在尝试为我的网站创建一个简单的消息功能,但我无法从2列(**from**列和**to**列)获取不同的数据

你会在图片上看到示例数据
我怎样才能获得"1,4,23,45,345"的回报?
您应该将两个列合并,然后筛选不同的值:
select distinct T.from_to from
( select `from` as from_to
from messages
union
select `to` as from_to
from messages
) T
Run Code Online (Sandbox Code Playgroud)
如果你真的需要一个逗号分隔的字符串,请使用GROUP_CONCAT([DISTINCT]聚合函数.
编辑:
你应该把解决方案标记为Gerald的答案.在测试union运算符和重读mysql union运算符文档之后,默认情况下,mysql过滤不同的值:
mysql> create table ta( a int );
Query OK, 0 rows affected (0.05 sec)
mysql> insert into ta values (1),(1),(2);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from ta
-> union
-> select * from ta;
+------+
| a |
+------+
| 1 |
| 2 |
+------+
2 rows in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
那么,最后的查询是:
select `from` as from_to
from messages
union distinct
select `to` as from_to
from messages
Run Code Online (Sandbox Code Playgroud)
请注意,这distinct不是强制性的.
只有当您需要逗号sparate字符串时,才需要第一个解决方案:
select distinct GROUP_CONCAT( distinct T.from_to from )
( select `from` as from_to
from messages
union
select `to` as from_to
from messages
) T
Run Code Online (Sandbox Code Playgroud)