将列分组为行SQL

时间:2013-06-27 19:58:52

标签: mysql sql

我想在一行上对功能和值进行分组。有人推荐GROUP_CONCAT,但是当我这样做时,我失去了所有其他产品。这是我目前的SQL调用

SELECT ps_product_lang.name, CONCAT(ps_feature_lang.name) AS feature, ps_feature_value_lang.value  FROM ps_product LEFT JOIN ps_product_lang ON ps_product_lang.id_product = ps_product.id_product LEFT JOIN ps_feature_product ON ps_feature_product.id_product = ps_product.id_product LEFT JOIN ps_feature_lang ON ps_feature_lang.id_feature = ps_feature_product.id_feature LEFT JOIN ps_feature_value_lang ON ps_feature_value_lang.id_feature_value = ps_feature_product.id_feature_value

这给了我这样的回报

name                 feature    value
MRO Plus Heavy Pad       Height 5
MRO Plus Heavy Pad       Width  12
MRO Plus Heavy Pad       Depth  13
MRO Plus Heavy Pad       Weight 15
ENV810™ Sorbent Boom     Height 88
ENV810™ Sorbent Booms    Width  50
ENV810™ Sorbent Booms    Depth  23
ENV810™ Sorbent Booms    Weight 45
ENV510™ Sorbent Booms    NULL   NULL
MRO Plus Medium Pad      NULL   NULL

当我尝试GROUP_CONCAT时,我的结果如下所示。

Name                Feature                                                 Value
MRO Plus Heavy Pad  Height,Width,Depth,Weight,Height,Width,Depth,Weigh...   5,12,13,15,88,50,23,45

在MySQL中是否有办法让它看起来像这样

Name                    Feature                           Value
MRO Plus Heavy Pad      Height, Width, Depth, Weight      5, 12, 13, 15
ENV810 Sorbent Boom     Height, Width, Depth, Weight      88, 50, 23, 45
ENV510 Sorbent Boom     Null                              Null
MRO Plus Medium pad     Null                              Null

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

GROUP_CONCAT是MySQL specific aggregate function,它与GROUP BY子句一起使用。您必须在查询末尾指定带有GROUP_BY子句的列才能使其正常工作。

样品:

SELECT ps_product_lang.name, GROUP_CONCAT(ps_feature_lang.name) AS feature, ps_feature_value_lang.value FROM ps_product LEFT JOIN ps_product_lang ON ps_product_lang.id_product = ps_product.id_product LEFT JOIN ps_feature_product ON ps_feature_product.id_product = ps_product.id_product LEFT JOIN ps_feature_lang ON ps_feature_lang.id_feature = ps_feature_product.id_feature LEFT JOIN ps_feature_value_lang ON ps_feature_value_lang.id_feature_value = ps_feature_product.id_feature_value GROUP BY ps_product_lang.name