【问题标题】:GROUP_CONCAT on two tablesGROUP_CONCAT 在两个表上
【发布时间】:2014-02-13 16:48:07
【问题描述】:

我有两个表,具有独立的 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

这些查询向我返回了重复的结果,尽管 8as in,所有结果来自 a 两次,所有结果来自 b 两次)

【问题讨论】:

  • 可以使用UNION 帮助吗?

标签: mysql sql concatenation


【解决方案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

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      以下查询将生成您想要的。 您可以使用 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
          )
      

      【讨论】:

        【解决方案4】:

        如果您想要重复,请使用union all。如果您不想重复,请使用union。 无论哪种情况,您需要的查询如下:

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

        【讨论】:

          猜你喜欢
          • 2015-12-31
          • 2017-04-27
          • 2012-03-25
          • 2014-07-19
          • 2019-04-28
          • 2012-07-28
          • 2021-08-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多