简体   繁体   English

sql与众不同,获取2列

[英]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) 我正在尝试为我的网站创建一个简单的消息功能,但无法从2列( **from**列和**to**列)中获取不同的数据

在此处输入图片说明

you see examples datas on the picture 您在图片上看到示例数据

how can I get the return "1,4,23,45,345"? 如何获得退货“ 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. 如果确实需要用逗号分隔的字符串,请使用GROUP_CONCAT([DISTINCT]聚合函数。

EDITED : 编辑

You should mark as solution Gerald answer. 您应该将Gerald答案标记为解决方案。 After test union operator and reread mysql union operator documentation , by default, mysql filter for distinct values: 在测试并操作符并重新阅读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)

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. 注意, distinct不是强制性的。

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. 在MySQL中,union默认选择不同的行。 You would use UNION ALL to allow for duplicates. 您将使用UNION ALL允许重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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