不创建表格如何使用json_populate_recordset?

12

我在我的数据库中有一张表,其中有一个列包含json记录。

id | json_records
---+-------------
 0 | "[{'x1' : 1234, 'x2' : 5678},{'x1' : 2345, 'x2' : 6789}]'
 1 | "[{'x1' : 4321, 'x2' : 8765},{'x1' : 5432, 'x2' : 9876}]'

我想要类似这样的东西:

id |   x1 |   x2
---+------+-----
 0 | 1234 | 5678
 0 | 2345 | 6789
 1 | 4321 | 8765
 1 | 5432 | 9876

但是我在尝试查询的时候遇到了麻烦:

select json_populate_recordset(json_records) from my_table

我看到的使用json_populate_recordset的例子都是将结果插入到一个表中,但我只想返回结果。有没有一种方法可以在不创建新表的情况下实现这一点?


你能指出你发现的其他好例子吗?我发现在使用这些类型的json操作时,世界上似乎缺乏相关文档。 - Aidan Kane
2个回答

22

您需要创建一个新类型以传递给函数(请注意,由于json_populate返回一个json_type,因此您需要使用(row).*符号来获取各个字段):

CREATE type json_type AS (x1 int, x2 int);

 SELECT id, (json_populate_recordset(null::json_type, json_records)).* FROM my_table;

1

这是另一个使用 PostgreSQL 11 上的 JSON 字符串的示例

drop TYPE json_test;
create TYPE json_test AS (id_item int, id_menu varchar(100));
select * from json_populate_recordset(null::json_test,'[{"id_item":1,"id_menu":"34"},{"id_item":2,"id_menu":"35"}]')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接