实现嵌套的group_concat

时间:2017-06-14 21:50:00

标签: mysql

我有这个问题:

select  p.id,
        p.price,
        concat('[',group_concat(concat('{',concat_ws(',', concat('color:', pc.color),concat('sizeName:',cs.size_name)),'}')),']') as variety

        from tbl_products as p

    inner join tbl_product_colors as pc on p.id = pc.product_id
    left join tbl_color_sizes as cs on pc.id = cs.product_color_id

group by p.id;

查询以上输出:

Id | price  | variety
1  | 1000  | [ {color:FFFFFF, sizeName:XL} , {color:FFFFFF, sizeName:X} ]

但我想要的输出是:

Id | price  | variety
1  | 1000  | [ {color:FFFFFF, sizes: [ {sizeName: XL} , {sizeName: L} ] } ]

问题:如何在此上下文或任何其他函数(除了JSON函数)中使用group_concat来实现所需的输出?

1 个答案:

答案 0 :(得分:2)

几乎在所有情况下,需要嵌套聚合的结果都需要“嵌套”查询。您将在外部分组维度上分组的子查询中执行“大小列表”,并在外部查询中将这些字段组合在一起;然后在外部查询中聚合具有与它们连接的“大小列表”的字段。

这样的东西,但为了便于阅读,我省略了大部分额外的CONCAT。

SELECT subQ.id, subQ.price
   , GROUP_CONCAT(CONCAT(subQ.color, ': ', subQ.sizeList)) AS variety
FROM (
   SELECT p.id, p.price, pc.color
      , GROUP_CONCAT(cs.size_name) AS sizeList
   FROM tbl_products AS p
   INNER JOIN tbl_product_colors AS pc ON p.id = pc.product_id
   LEFT JOIN tbl_color_sizes AS cs ON pc.id = cs.product_color_id
   GROUP BY p.id, p.price, pc.color
) AS subQ
GROUP BY subQ.id, subQ.price
;