如何将 PostgreSQL hstore 列转换为行?

Der*_*har 4 sql postgresql hstore

什么 SQL 查询会将PostgreSQL hstore列转换为常规表,其中所有 hstore 行中的不同键形成表中的列,并且值填充相应列中的行?

例如,如何转换 hstore 列

hstore
------------------------------------
"a"=>"1", "b"=>"2", "c"=>"3"
"a"=>"4", "b"=>"6", "c"=>"5", "d"=>7
"a"=>"8", "b"=>"3", "c"=>"8"
Run Code Online (Sandbox Code Playgroud)

进入“等效”表

a   b   c   d
---------------
 1 | 2 | 3 |
 4 | 6 | 5 | 7 
 8 | 3 | 8 |
Run Code Online (Sandbox Code Playgroud)

其中不同的 hstore 键 a、b、c 和 d 形成表中的列,并且它们的值填充每列中的行?

小智 5

您无法动态执行此操作,但如果您创建与输出匹配的类型,则可以执行此操作。

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;
Run Code Online (Sandbox Code Playgroud)

返回:

一个 | 乙| C
--+---+--
1 | 2 |  
1 | 2 | 3
1 | |  

请注意,如果您有一个与所需列匹配的表,您也可以使用“表类型”。