2014-02-13 20 views
0

我有兩個表,與獨立的ID(不能通過連接連接),我想查詢並獲得兩列的GROUP_CONCAT。GROUP_CONCAT在兩個表

示例:表「a」具有ID:1,2,3,。表「b」具有ID:10,11

最終結果應該是:1,2,3,10,11

我已經嘗試了幾個疑問:

SELECT CONCAT_WS(',', GROUP_CONCAT(a.id), GROUP_CONCAT(b.id)) AS combined FROM a, b 

SELECT GROUP_CONCAT(a.id, b.id) AS combined FROM a, b 

這些查詢返回我重複的結果雖然,所有8AS從兩次結果和從b的兩倍,以及所有結果)

+0

可以使用'UNION'幫助嗎? –

回答

1

嘗試union all

select group_concat(ab.id) as ids 
from ((select id from a 
    ) union all 
     (select id from b 
    ) 
    ) ab; 

你的查詢都是做交叉連接的表之間的,所以交叉後數據連接是:

a.id  b.id 
1   10 
1   11 
2   10 
2   11 
3   10 
3   11 

union all後,數據是:

ab.id 
    1 
    2 
    3 
10 
11 
0

如果您想要複製品,請使用union all。如果您不想重複,請使用union。 在這兩種情況下,你需要查詢如下:

select group_concat(id) from 
(select id from a 
    union 
    select id from b) as ids; 
0

下面的查詢將生成你想要的。 您可以使用table_position動態列來決定哪個表先行。

Select group_concat(id order by table_position) from 
    (
     select id, 1 as table_position from a 
     union all 
     select id, 2 as table_position from b 
    )