mysql选择动态行值作为列名如下

时间:2015-06-26 05:06:10

标签: mysql sql

这是我的mysql查询

SELECT research_id,
@availability:=if(product_id=4,value,'') AS availability,
@cooler:=if(product_id=5,value,'') AS Cooler,
@coolerLocation:=if(product_id=9,value,'') AS CoolerLocation
FROM research_product_details rpd
LEFT JOIN products p
ON rpd.product_id = p.id
WHERE product_id = 4 OR product_id = 5 OR product_id = 9
ORDER BY research_id ASC, product_id ASC

我得到了这个结果

enter image description here

这不是我想要的结果,我想要这样,

enter image description here

1 个答案:

答案 0 :(得分:2)

GROUP BYMAX()一起使用以展平表格

SELECT research_id,
    MAX(if(product_id=4,value, NULL)) AS availability,
    MAX(if(product_id=5,value, NULL)) AS Cooler,
    MAX(if(product_id=9,value, NULL)) AS CoolerLocation
FROM research_product_details rpd
LEFT JOIN products p
ON rpd.product_id = p.id
WHERE product_id = 4 OR product_id = 5 OR product_id = 9
GROUP BY research_id 
ORDER BY research_id ASC, product_id ASC