2013-04-18 35 views
3

什麼SQL查詢會將PostgreSQLhstore列轉換爲常規表,其中所有hstore行中的不同關鍵字形成表中的列,並且這些值將填充相應列中的行?如何將PostgreSQL hstore列翻譯成一行?

例如,我如何轉換hstore柱

hstore 
------------------------------------ 
"a"=>"1", "b"=>"2", "c"=>"3" 
"a"=>"4", "b"=>"6", "c"=>"5", "d"=>7 
"a"=>"8", "b"=>"3", "c"=>"8" 

成 「等效」 表

a b c d 
--------------- 
1 | 2 | 3 | 
4 | 6 | 5 | 7 
8 | 3 | 8 | 

其中不同hstore鍵的a,b,c和d形成在列表和它們的值填充每列中的行?

回答

4

你不能動態地做到這一點,但你可以做到這一點,如果你創建一個匹配你的輸出的類型。

create table foo (data hstore); 
create type foo_type as (a text, b text, c text); 

insert into foo (data) 
values 
('a => 1, b => 2'), 
('a => 1, b=>2, c => 3'), 
('a => 1'); 

select (populate_record(null::foo_type, data)).* 
from foo; 

回報:

 
a | b | c 
--+---+-- 
1 | 2 | 
1 | 2 | 3 
1 | | 

請注意,您還可以使用「表型」,如果你有你想要的列相匹配的表。

0

我知道這個問題有答案,但我遇到了類似的問題。我需要轉換hstore值,以便我可以直接將數據插入到表中。 這是我已經得到了解決:

INSERT INTO foo 
SELECT (populate_record(null::foo, 'a => 1, b=>2, c => 3'::hstore)).*; 

當然,hstore列必須在表中,否則會被忽略。 希望這可以幫助其他像我這樣在這裏結束的人。 :)