2017-10-10 75 views
0

的在嘗試從hstore(postgreql)插入值,以一個更通用的表插入基於選擇hstore列

在我的車表,我的論文領域

id 
fields (hstore) 

我的存儲表,我有這些字段

id 
key 
value 
car_id 
date 

如何循環到我的字段屬性插入鍵,值到我的存儲表。

有沒有辦法用select命令做到這一點?

回答

2

示例數據:

insert into car values 
(1, 'brand=>ford, color=>yellow'), 
(2, 'brand=>volvo, mileage=>50000, year=>2015'); 

使用功能each(hstore)得到hstore柱對(key, value)

select id, key, value 
from car, each(fields); 

id | key | value 
----+---------+-------- 
    1 | brand | ford 
    1 | color | yellow 
    2 | year | 2015 
    2 | brand | volvo 
    2 | mileage | 50000 
(5 rows)  

INSERT命令可能是這樣的:

insert into store (car_id, key, value) 
select id, key, value 
from car, each(fields);