MYSQL - 如何将值分隔为列 - concat

时间:2014-09-30 12:30:57

标签: mysql sql rows multiple-columns group-concat

目前我在phpmyadmin中输入了以下mysql代码:

select Product_ID, group_concat(`Name` separator ',') as `Spec` 
from 
( 
select Product_ID, concat(`Name`, ':', 
group_concat(`Value` separator ',')) as `Name` 
from product_spec_list  
group by Product_ID, `Name` 
) tbl 
group by Product_ID 

产生:

ID              Name
3   Shielded:0,Type:General Purpose
4   Shielded:0,Type:General Purpose

等。带有一长串产品ID列表,其名称和值之间用:和,分隔。

如何将值分隔为'名称'?

E.g。

ID Shielded      Type 
3     0     General Purpose 
4     0     General Purpose 

大约有40个不同的名称。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我没有测试过,但我在想这样的事情:

SELECT Product_ID AS `ID`
  , GROUP_CONCAT(IF(Name="Shielded", values, "") SEPARATOR "") AS `Shielded`
  , GROUP_CONCAT(IF(Name="Type", values, "") SEPARATOR "") AS `Type`
FROM
  (SELECT Product_ID, Name, GROUP_CONCAT(value SEPARATOR ',') AS values
   FROM product_spec_list
   GROUP BY Product_ID, Name
  ) AS subQ
GROUP BY Product_ID;