使用多个联接在同一查询中对数据进行分组

时间:2014-09-21 02:21:55

标签: mysql sql concat group-concat

我有几张桌子:

products: id (int), name (varchar)
colors: id (int), name (varchar)
sizes: id (int), name (varchar)
products_colors: color_id (int), product_id (int)
products_sizes: size_id (int), product_id (int)

我想只生成一个返回所有信息的查询(而不是3个查询,1个用于产品,1个用于颜色,1个用于大小) 我发现我可以使用GROUP_CONCAT做一些“体面的”,但是查询返回重复数据,不确定是否发生这种情况,因为GROUP_CONCAT或JOINS

SELECT products.id, products.name, CONCAT("[", GROUP_CONCAT("'", colors.name, "'"), "]")     colors, CONCAT("[", GROUP_CONCAT("'", sizes.name, "'"), "]") sizes
FROM products 
LEFT JOIN products_sizes ON products_sizes.product_id = products.id
LEFT JOIN sizes ON sizes.id = products_sizes.size_id
LEFT JOIN products_colors ON products_colors.product_id = products.id
LEFT JOIN colors ON colors.id = products_colors.color_id
GROUP BY products.id

请注意,我使用CONCAT将分组数据格式化为JSON 如果products_colors和products_sizes中存在匹配项,则数据将在GROUP_CONCAT中重复

无论是否有颜色或尺寸,我都需要退回所有产品

1 个答案:

答案 0 :(得分:1)

尝试向group_concat函数添加distinct:

SELECT products.id,
       products.name,
       case when colors.name is null then '[]' else
       CONCAT("[", GROUP_CONCAT(distinct "'", colors.name, "'"), "]") end as colors,
       case when sizes.name is null then '[]' else
       CONCAT("[", GROUP_CONCAT(distinct "'", sizes.name, "'"), "]") end as sizes
  FROM products
  LEFT JOIN products_sizes
    ON products_sizes.product_id = products.id
  LEFT JOIN sizes
    ON sizes.id = products_sizes.size_id
  LEFT JOIN products_colors
    ON products_colors.product_id = products.id
  LEFT JOIN colors
    ON colors.id = products_colors.color_id
 GROUP BY products.id, products.name