两个表上的GROUP_CONCAT

时间:2014-02-13 16:48:08

标签: mysql sql concatenation

我有两个表,有独立的id(不能通过连接连接),我想查询并获得两列的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

这些查询返回我的重复结果虽然8位,所有结果来自两次,所有结果来自b两次)

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

答案 2 :(得分:0)

如果您想要重复,请使用union all。如果您不想要重复,请使用union。 在任何一种情况下,您需要的查询如下:

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

答案 3 :(得分: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
    )