我正在尝试弄清楚如何使用 jsonb_to_recordset
和自定义类型扩展 JSONB 字段。
Postgres 11.4。
这只是一个测试用例,但目前我正在尝试计算语法。我有一个名为 data_file_info
的表,其中包含一个名为 table_stats
的 JSONB 字段。 JSONB 字段始终包含具有相同结构的 JSON 数组:
[
{"table_name":"Activity","record_count":0,"table_number":214},
{"table_name":"Assembly","record_count":1,"table_number":15},
{"table_name":"AssemblyProds","record_count":0,"table_number":154}
]
以下代码可以正确运行:
from data_file_info,
jsonb_to_recordset(table_stats) as table_stats_splat (
table_name text,
record_count integer,
table_number integer
)
我想要做的是传递自定义类型定义,而不是上面显示的长格式列定义列表。这是匹配类型:
create type data.table_stats_type as (
table_name text,
record_count integer,
table_number integer)
我见过的一些示例,文档说,您可以在第一个参数中使用 null:row_type
转换来提供类型名称 jsonb_to_recordset
。我发现的示例使用内联 JSON,而我正在尝试提取存储的 JSON。我做了一些尝试,但都失败了。下面是两个试验,有错误。有人能指出我正确的语法吗?
失败:
select table_stats_splat.*
from data_file_info,
jsonb_populate_recordset(null::table_stats_type, data_file_info) as table_stats_splat;
-- ERROR: function jsonb_populate_recordset(table_stats_type, data_file_info) does not exist
-- LINE 4: jsonb_populate_recordset(null::table_stats_type, dat...
^
-- HINT: No function matches the given name and argument types. You might need to add explicit type casts. (Line 4)
失败:
select *
from jsonb_populate_recordset(NULL::table_stats_type, (select table_stats from data_file_info)) as table_stats_splat;
-- ERROR: more than one row returned by a subquery used as an expression. (Line 2)
我无疑错过了一些非常明显的东西,希望有人能提出建议。
最佳答案
使用列作为第二个参数:
select table_stats_splat.*
from data_file_info,
jsonb_populate_recordset(null::table_stats_type, table_stats) as table_stats_splat;
关于postgresql - 将行类型传递给 jsonb_to_recordset 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58441656/