2015-11-05 77 views
-2

我有兩列:發件人,收件人在我的表中。我想獲得發送者或接收者等於b的列中的獨特列表,然後將它們連接到字符串中。MYSQL兩列不同

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

結果集應該看起來像A,B,C,E

我應該怎麼做來實現這一目標?

+0

如果你連接它們,你有兩個字母,所以結果'a,b,c,e'會是兩對。第二對不包含'b',所以我很好奇你是如何得到這個結果的...... – GolezTrol

+0

另外,這可能可以在SQL中完成。你在尋找一個MySQL解決方案嗎?如果是這樣,請刪除PHP標記,因爲這對查詢本身無關緊要。 – GolezTrol

+0

爲了解決您的問題,如果他們幫助您,請將任何一個答案標記爲已接受。 – zedfoxus

回答

1

你可以做2個被聯合查詢得到的值。聯盟應該消除重複。然後,你可以使用它作爲一個子查詢並做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 
+0

它像一個魅力。謝謝! – user2126081

1

看看這個線程: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 
1

試試這個:

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 | 
+---------+ 

如果你想按字母順序排序,你可以用select 'b' order by sender取代select 'b'會讓你得到a,b,c,e作爲結果