转动mysql表不起作用

时间:2015-07-24 12:51:35

标签: mysql pivot

我已经在这里阅读了artfulsoftware和众多主题,但仍然无法理解为什么我无法使其发挥作用。

我有一个非常简单的表(productProperties pp),有三列:

prodName propName propValue

我想查询,因此它将表示为(例如)

prodName Color  Weight Adhesive
nail1    black  1lbs   3m 
nail2    silver 0.5lbs 3m

我尝试了什么:

select 
    pp.prodName,
     CASE pp.propName
        WHEN 'Color' THEN pp.propValue
        ELSE NULL
    END as 'Color',

   CASE pp.propName
        WHEN 'Weight' THEN pp.propValue
        ELSE NULL
    END as 'Weight',

   CASE pp.propName
        WHEN 'Adhesive' THEN pp.propValue
        ELSE NULL
    END as 'Adhesive'      
from
    ProductsProperties as pp    
group by pp.prodName;

除了prodName

,我得到所有的NULL

例如:

prodName propName   propValue
nail1    Color      black
nail1    Adhesive   3M
nail2    Weight     1lbs
nail3    Color      black
nail3    Adhesive   3M
nail5    Weight     1lbs

以上查询结果为:

 prodName, Color,   Weight, Adhesive
 nail1,    black,   NULL,   NULL
 nail2,    NULL,    1lbs,   NULL
 nail3,    black,   NULL,   NULL
 nail5,    NULL,    1lbs,   NULL

2 个答案:

答案 0 :(得分:1)

使用join的解决方案:

select distinct pp1.prodName, 
       pp2.propValue as 'Color', 
       pp3.propValue as 'Adhesive', 
       pp4.propValue as 'Weight' 
from ProductsProperties pp1 
  left join ProductsProperties pp2 on pp1.prodName = pp2.prodName and pp2.propName = 'Color'
  left join ProductsProperties pp3 on pp1.prodName = pp3.prodName and pp3.propName = 'Adhesive'
  left join ProductsProperties pp4 on pp1.prodName = pp4.prodName and pp4.propName = 'Weight';

答案 1 :(得分:0)

您需要将CASE包装到GROUP_CONCAT()

SELECT
    pp.prodName,
    GROUP_CONCAT(DISTINCT CASE pp.propName
        WHEN 'Color' THEN pp.propValue
        ELSE NULL
    END) AS'Color',

    GROUP_CONCAT(DISTINCT CASE pp.propName
        WHEN 'Weight' THEN pp.propValue
        ELSE NULL
    END) AS 'Weight',

    GROUP_CONCAT(DISTINCT CASE pp.propName
        WHEN 'Adhesive' THEN pp.propValue
        ELSE NULL
    END) AS 'Adhesive'      
FROM
    ProductsProperties AS pp    
GROUP BY pp.prodName;