[英]sql distinct, getting 2 columns
我正在嘗試為我的網站創建一個簡單的消息功能,但無法從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
如果確實需要用逗號分隔的字符串,請使用GROUP_CONCAT([DISTINCT]聚合函數。
編輯 :
您應該將Gerald答案標記為解決方案。 在測試並操作符並重新閱讀mysql並操作符文檔后 ,默認情況下,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
不是強制性的。
僅當您需要逗號備用字符串時,才需要第一個解決方案:
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
select from as ft from messages
union
select to as ft from messages
在MySQL中,union默認選擇不同的行。 您將使用UNION ALL允許重復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.