Group_concat,如果其他列相等,则将列连接到一行

时间:2014-09-11 17:28:35

标签: mysql sql

在包含衣服的数据库上运行以下查询,我得到result,其中我有同一产品的多行,唯一的区别是大小列。

SQL QUERY:

SELECT 
categories.name AS "category",
color_variant.pcode AS "code",
stock.size AS "size",
color_variant.price AS "price"

FROM 
categories, product, color_variant, stock

WHERE
categories.id = product.category_id AND
product.id = color_variant.product_id AND
color_variant.id = stock.color_variant_id 

ORDER BY 
categories.id

我想加入每个产品的大小行,所以我得到像

这样的东西
 category    code               sizes               price
  jean   1018918053   24,25,26,27,28,29,30,31,32   119.99
  jean   1018916407   26                           159.99
  jean   1018917373   31                           159.99
  jean   1018917354   25                           109.99
  jean   1018919115   24,25,26,27,28,29,30,31,32   129.99
  jean   1018913449   24,25,26,27                  109.99

我通过将stock.size AS "size",替换为

来尝试GROUP_CONCAT

GROUP_CONCAT(DISTINCT stock.size ORDER BY stock.size SEPARATOR ', ') AS "sizes",

但这给了我一行结果,即使我将它用作子查询,每个大小的行都会被连接,

category    code                    sizes                        price
 jean    1018918053  1,105,11-12,115,2-3,23,24,25,26,27,28,2...  119.99

关于我做错了什么的任何想法?或者我如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

添加

GROUP BY categories.name, color_variant.pcode, color_variant.price 

ORDER BY

之前