将行组合到mysql中的单个行中

时间:2016-07-19 08:05:30

标签: php mysql

我在合并两个查询时遇到问题:

SELECT f.attribute_name, s.value as htc 
FROM  attributes f
left join `car_type` c on f.type_id=c.id 
left join mode m on m.id = f.mode_id 
left join settings s on f.id=s.attr_id
where c.id=1 and f.mode_id = 1

在提供此查询时,我得到了以下输出,如图像

enter image description here

SELECT f.attribute_name, s.value as ct
FROM  attributes f
left join `car_type` c on f.type_id=c.id
left join mode m on m.id = f.mode_id
left join settings s on f.id=s.attr_id
where c.id=2 and f.mode_id = 1

对于第二个查询,我得到了输出,如图像

enter image description here

我希望在两个查询中属性名称相同的同一行中获取ct和htc值。

1 个答案:

答案 0 :(得分:2)

这似乎是一个表格枢轴问题,不确定它是否有效,但尝试一下:

SELECT
    f.attribute_name,
    MAX(CASE WHEN c.id = 1 THEN s.value ELSE NULL END) AS htc,
    MAX(CASE WHEN c.id = 2 THEN s.value ELSE NULL END) AS ct
FROM attributes f
LEFT JOIN `car_type` c ON f.type_id=c.id
LEFT JOIN MODE m ON m.id = f.mode_id
LEFT JOIN settings s ON f.id=s.attr_id
WHERE c.id IN (1,2) AND f.mode_id = 1
GROUP BY f.attribute_name