2012-01-02 37 views
1

我试图创建自己的网站一个简单的消息功能,但我无法从2列(**from**柱和**to**列)SQL不同,得到2列

enter image description here

你会得到不同的DATAS看到图片上的示例数据

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

+0

能否请您发布您的查询? – 2012-01-02 14:16:00

+0

我需要'from'不同DATAS和'to'列 – 2012-01-02 14:19:25

+0

请看看这里: http://stackoverflow.com/questions/546804/select-distinct-from-multiple-fields-using-sql – 2012-01-02 14:19:36

回答

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字符串的第一个解决方案是必要的:

​​
+1

谢谢你danihp,你刚刚救了我的一天:| – 2012-01-02 14:23:45

+0

因为UNION默认选择不同的行,所以不需要外部不同。 UNION ALL允许重复。 – 2012-01-02 14:25:14

+0

@ GeraldP.Wright,是阅读更新的答案。 – danihp 2012-01-02 14:34:28

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

在MySQL工会默认情况下选择不同的行。你会使用UNION ALL来允许重复。

+0

是的,这是解决方案,在我的回答+1中评论。 – danihp 2012-01-02 14:33:02

+0

@Rothzerg,请将此答案标记为解决方案。 – danihp 2012-01-02 14:36:12