简体   繁体   English

两列的MYSQL不同

[英]MYSQL Distinct for two column

I got two columns: sender, receiver in my table.我有两列:发送者,我的表中的接收者。 I want to get the distinct for both column where sender or receiver equal to b and then concat them into string.我想为发送者或接收者等于 b 的两列获取不同的值,然后将它们连接成字符串。

....................
sender  |  receiver
....................
  a            b
  c            b
  b            a
  b            c
  d            f
  b            e
  b            e
  e            b

The result set should look like a,b,c,e结果集应该看起来像 a,b,c,e

What should I do to achieve this?我应该怎么做才能实现这一目标?

Take a look at this thread : MySQL SELECT DISTINCT multiple columns看看这个线程: MySQL SELECT DISTINCT multiple columns

SELECT DISTINCT value FROM
( 
    SELECT DISTINCT a AS value FROM my_table
    UNION 
    SELECT DISTINCT b AS value FROM my_table
    UNION 
    SELECT DISTINCT c AS value FROM my_table 
) AS derived

You can just do 2 unioned queries to get the values.您只需执行 2 个联合查询即可获取值。 Union should eliminate the duplicates. Union 应该消除重复项。 Then you can use that as a sub query and do a GROUP_CONCAT on the results:-然后您可以将其用作子查询并对结果执行 GROUP_CONCAT:-

SELECT GROUP_CONCAT(aCol)
FROM
(
    SELECT sender AS aCol
    FROM SomeTable
    WHERE sender = 'b'
    OR receiver = 'b'
    UNION
    SELECT receiver AS aCol
    FROM SomeTable
    WHERE sender = 'b'
    OR receiver = 'b'
) sub0

Try this:尝试这个:

create table test (sender char(1), receiver char(1));    
insert into test values ('a','b'), ('c','b'), ('b','a'), ('b','c'), ('d','f'), ('b','e'), ('b', 'e'), ('e', 'b');

select group_concat(sender  separator ',') as result 
from (
  select sender from test where receiver = 'b' 
  union
  select 'b'
) alias;

+---------+
| result  |
+---------+
| a,c,e,b |
+---------+

If you want alphabetical ordering, you can replace select 'b' with select 'b' order by sender and you will get a,b,c,e as the result如果您想要按字母顺序排序,您可以将select 'b'替换为select 'b' order by sender ,您将得到a,b,c,e作为结果

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

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