Pergunta

I have a table structure in MySQL where I have the following structure:

home_id, home_name, dateadded

I have another table called specs with the following structure:

home_id, spec_key, spec_value

In it I can have entries like the following:

1, price, 500000
1, location, 90210
1, rooms, 3
1, washrooms, 3
1, furnished_basement, 0
2, location, 14410
2, garage_size, 3
2, price, 335000

For search purposes, I'd like to denormalize the above. The table (denormalized_homes) structure would look something like:

home_id, price, location, rooms, washroom, furnished_basement, garage_size, dateadded

As you can see from the above, a) not all entries have a value for all columns. b) The table structure is not conducive to INSERT INTOdenormalized_homesselect * fromspecs type queries. I also can't used stored procedures or triggers (host regulations).

The tactic I've taken so far is to insert home_id into the denormalized_homes table, and then run through each field in spec with something like the following query:

UPDATE `denormalized_homes` dh, specs s SET dh.price = s.spec_value WHERE dh.home_id = s.home_id AND s.spec_key = "price";

Creating a query for each possible column and then running them works. I'm just thinking there must be a better way, is there?

Foi útil?

Solução

I think you could do something like this:

INSERT INTO denormalized_homes ()

SELECT h.home_id,
       price.spec_value price,
       location.spec_value location,
       rooms.spec_value rooms,
       washroom.spec_value washroom,
       furnished_basement.spec_value furnished_basement,
       garage_size.spec_value garage_size,
       h.date_added

FROM   homes h

       LEFT JOIN specs price
       ON price.home_id = h.home_id and spec_key = 'price'

       LEFT JOIN specs location
       ON price.home_id = h.home_id and spec_key = 'location'       

       LEFT JOIN specs rooms
       ON price.home_id = h.home_id and spec_key = 'rooms'

       LEFT JOIN specs washroom
       ON price.home_id = h.home_id and spec_key = 'washroom'

       LEFT JOIN specs furnished_basement
       ON price.home_id = h.home_id and spec_key = 'furnished_basement'

       LEFT JOIN specs garage_size
       ON price.home_id = h.home_id and spec_key = 'garage_size'
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top