2012-01-02 36 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