2016-12-02 59 views
0

我有一个带有两个不同表格的数据库,第一个名为'House',包含以下列:id, name, updated_at。我的第二个表格名为'House_meta',包括以下列:house_id, name, value。在元表中我有(例如)以下数据:SQL:将多行值作为列加入

house_ id  name  value 
1    street  123 streetname 
1    color  black 
1    city  chicago 
1    image  image-1.jpg 
1    image  image-2.jpg 
1    image  image-3.jpg 

我需要加入这些表,以便每个房子条目只在一行上。我的问题是图像,他们都必须在同一行,并可能像图像1,图像2,等等。我当前的SQL输出:

SELECT 
    house.id AS house_id, 
    house.name AS housename, 
    updated_at 
    max(case when house_meta.name = 'street' then house.value end) as street, 
    max(case when house_meta.name = 'color' then house.value end) as color, 
    max(case when house_meta.name = 'city' then house.value end) as city, 
    max(case when house_meta.name = 'image' then house.value end) as image 
FROM house 
    join house_meta on house.id = house_meta.house_id 
group by 
    house.id 

这只(自然)的结果只作为一个图像添加。我怎样才能做到这一点,以便所有的图像最终在一行?

我多么希望它返回:

house_id updated_at street   color city  image1  image2  image3 
1   2016-12-02 123 streetname black chicago image-1.jpg image-2.jpg image-3.jpg 
+0

你想看看'pivoting'概念 – Rahul

回答