2017-06-14 179 views
0

我有這樣的查詢:實現嵌套GROUP_CONCAT

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} ] } ] 

問題:如何在此上下文中使用group_concat或其他函數(除了JSON函數)來實現所需的輸出?

+0

如果產品1有多種顏色,那麼期望的輸出是什麼? – Uueerdo

+0

[{color:FFFFFF,sizes:[{sizeName:XL},{sizeName:L}]},{color:F2F2F2,sizes:[{sizeName:XL}]}] – Sajad

+0

這將是一個'字段值? – Uueerdo

回答

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 
;