1到多个模式的非规范化

时间:2012-10-10 13:20:29

标签: mysql denormalization

我在MySQL中有一个表结构,我有以下结构:

  

home_id,home_name,dateadded

我有另一个名为specs的表,其结构如下:

  

home_id,spec_key,spec_value

在其中,我可以输入以下内容:

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

出于搜索目的,我想对上述内容进行反规范化。表(denormalized_homes)结构如下所示:

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

从上面可以看出,a)并非所有条目都包含所有列的值。 b)表结构不利于INSERT INTO denormalized_homes select * from规范类型查询。我也不能使用存储过程或触发器(主机规则)。

我到目前为止采取的策略是将home_id插入denormalized_homes表,然后使用以下查询运行规范中的每个字段:

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

为每个可能的列创建一个查询,然后运行它们。我只是觉得必须有更好的方法,是吗?

1 个答案:

答案 0 :(得分:1)

我认为你可以这样做:

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'