CREATE TABLE spec_property
(`spm_id` int, `spec_value` varchar(11), `product_name` varchar(55))
;
INSERT INTO spec_property
(`spm_id`, `spec_value`, `product_name`)
VALUES
(6, 'android', 'phone 1'),
(7, '4GB', 'phone 1'),
(7, '2GB', 'phone 2'),
(7, '2GB', 'phone 3'),
(11, '8mp', 'phone 1')
http://sqlfiddle.com/#!9/d38db
+--------+---------------------+---------------------+---------------------+
| spm_id | col1 | col 2 | col 3 |
+--------+---------------------+---------------------+---------------------+
| Name| phone1 | phone2 |phone3 |
| 6 | android | | |
| 7 | 4GB | 2GB | 2GB |
| 11 | 8mp | | |
+--------+---------------------+---------------------+---------------------+
我需要使用php的产品比较页面。我能够从mysql fetch查询中将行转换为列。问题是结果缺少标题的“product_name”。
答案 0 :(得分:0)
您可以在纯mysql中执行此操作(不理想,但会提供您想要的结果)
SELECT "Name" as spm_id, "phone1" as col1 , "phone2" as col2 ,"phone3" as col3
UNION
SELECT spm_id, GROUP_CONCAT(col1) as col1, GROUP_CONCAT(col2) as col2, GROUP_CONCAT(col3) as col3 FROM (
SELECT spm_id,
IF(product_name = "phone 1", spec_value,NULL) as col1 ,
IF(product_name = "phone 2", spec_value,NULL) as col2,
IF(product_name = "phone 3", spec_value,NULL) as col3
FROM spec_property
) AS tmp
GROUP BY spm_id
http://sqlfiddle.com/#!9/fc7c89/2/0
我认为你可以在php中做更好的工作(更具可扩展性),包括一些基本的查询和数组。