如何将postgres jsonb字段的属性插入键值表?

时间:2019-03-25 19:25:11

标签: postgresql select key-value jsonb

我想在单个语句中将jsonb值转换为键值表

我的示例代码:

CREATE TABLE public.searchdatacache
( querysig text, "values" jsonb );
INSERT INTO searchdatacache (querysig, values)
VALUES 
(
'ytApiSearch://Armageddon trailer',
'[
  {"VideoId"      : "xwseawq"},
  {"Title"        : "Armageddon"},
  {"PublishedAt"  : "2012/01/01"},
  {"Description"  : "Armageddon is a film"},
  {"ChannelTitle" : "Bruce Willis Movies"}
]'
)

SELECT jsonb_array_elements(values) from searchdatacache where querysig =    'ytApiSearch://Armageddon trailer'

返回:

"{"VideoId": "xwseawq"}"
"{"Title": "Armageddon"}"
"{"PublishedAt": "2012/01/01"}"
"{"Description": "Armageddon is a film"}"
"{"ChannelTitle": "Bruce Willis Movies"}"

由select语句返回的数据看起来还可以 到目前为止,但现在我想使用此选择语句 在“ INSERT INTO”语句中 填充键值表。

这些记录应填写到新的键值表中:

VideoId      | xwseawq
Title        | Armageddon
PublishedAt  | 2012/01/01
Description  | Armageddon is a film
ChannelTitle | Bruce Willis Movies

先谢谢 杰拉尔德

1 个答案:

答案 0 :(得分:1)

jsonb_array_elements子句中的fromjsonb_each_text一起使用,以准备插入键值对。

select s.key,s.value
       from searchdatacache cross join lateral
             jsonb_array_elements(values) as j(e)
    cross join lateral jsonb_each_text(j.e) as s(key,value);

Demo