sql distinct,获得2列

时间:2012-01-02 14:14:20

标签: mysql sql

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

enter image description here

你会在图片上看到示例数据

我怎样才能获得“1,4,23,45,345”的回报?

2 个答案:

答案 0 :(得分:7)

您应该将两个列合并,然后过滤不同的值:

select distinct T.from_to from
( select `from` as from_to
  from messages
  union
  select `to` as from_to
  from messages
) T

如果您真的需要逗号分隔的字符串,请使用GROUP_CONCAT([DISTINCT]聚合函数。

<强> EDITED

你应该将解决方案标记为杰拉德回答。在测试联合运算符和重读mysql union operator documentation之后,默认情况下,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)

然后,最终查询是:

  select `from` as from_to
  from messages
  union distinct
  select `to` as from_to
  from messages

请注意,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

答案 1 :(得分:4)

select from as ft from messages
union
select to as ft from messages

在MySQL中,默认情况下选择不同的行。您可以使用UNION ALL来允许重复。

相关问题