简体   繁体   中英

sql distinct, getting 2 columns

I'm trying to create a simple message feature for my website but I couldn't get distinct datas from 2 columns ( **from** column and **to** column)

在此处输入图片说明

you see examples datas on the picture

how can I get the return "1,4,23,45,345"?

You should to union both columns and then filter for distinct values:

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

if you really need all in a comma separate string, use GROUP_CONCAT([DISTINCT] aggregation function.

EDITED :

You should mark as solution Gerald answer. After test union operator and reread mysql union operator documentation , by default, mysql filter for distinct values:

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)

then, the final query is:

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

Notice that distinct is not mandatory.

Only if you need a comma sparate string the first solution is necessary:

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

In MySQL union selects distinct rows by default. You would use UNION ALL to allow for duplicates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM