简体   繁体   中英

Can a mysql query return all of an entities fields in single row?

I am trying to setup schema for buildings and all their info.

because the number of areas for a building can vary , I have stored the areas in a table "areas", where each area has a foreign key pointing to the primary key of the building they belong to.

What I want is to try and get all the info for a building on one line like:

--------------------------------------------------------------------
id |   address           | owner     | area 1  |  area 2   | area 3 |
--------------------------------------------------------------------
1  | 21  kingsbridge  st | claudia   | kitchen |  bathroom |  garage|
--------------------------------------------------------------------

Using a LEFT JOIN I can get the info, just not in the format Im after

I have set up a schema here http://www.sqlfiddle.com/#!9/83558/6

was hoping there is a query like maybe an aggregator function like GROUP BY or something? is this possible?

select x.pId, x.address, x.owner,
      max(x.area1) A1, max(x.area2) A2,max(x.area3) A3,max(x.area4) A4,max(x.area5) A5
from 
(
SELECT p.id pId, p.address, p.owner, a.id aId, a.property_id, a.area_name,
        case when a.area_name = 'kitchen' then a.area_name else null end as area1,
        case when a.area_name = 'garage' then a.area_name else null end as area2,
        case when a.area_name = 'checkout' then a.area_name else null end as area3,
        case when a.area_name = 'booths' then a.area_name else null end as area4,
        case when a.area_name = 'bathroom' then a.area_name else null end as area5
FROM   properties p
       LEFT JOIN areas a
              ON p.id = a.property_id
  ) as X
        GROUP BY pId, x.address, x.owner

But you need to know what are the distinct areas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM