Eva*_*oll 5 postgresql datatypes row composite-types
运行下面的命令,我得到“返回“记录”的函数需要一个列定义列表。
SELECT *
FROM json_to_record('{"a":1,"b":2,"c":3,"d":4}');
ERROR: a column definition list is required for functions returning "record"
LINE 1: SELECT * FROM json_to_record('{"a":1,"b":2,"c":3,"d":4}');
Run Code Online (Sandbox Code Playgroud)
没关系。我知道它想要什么。
SELECT *
FROM json_to_record('{"a":1,"b":2,"c":3,"d":4}')
AS (a int, b int, c int, d int);
Run Code Online (Sandbox Code Playgroud)
此外,在 PostgreSQL 中,所有表都已经有一个以相同名称创建的类型。
CREATE TABLE foo(a,b,c,d)
AS VALUES
(1,2,3,4);
Run Code Online (Sandbox Code Playgroud)
这将创建一个foo
链接到新创建的 table的内部类型foo
。不过,我可以很容易地创建一个类似的类型bar
。
CREATE TYPE bar AS (a int, b int, c int, d int);
Run Code Online (Sandbox Code Playgroud)
能够将返回的记录转换json_to_record()
为 bar会很棒。
SELECT *
FROM json_to_record('{"a":1,"b":2,"c":3,"d":4}')
AS foo; -- bar? anything?
Run Code Online (Sandbox Code Playgroud)
无论如何要满足具有类型的列定义列表?
使用json_populate_record
:
SELECT *
FROM json_populate_record(null::foo, '{"a":1,"b":2,"c":3,"d":4}')
Run Code Online (Sandbox Code Playgroud)
列匹配按名称完成,不存在的列将被静默忽略:
create type other_foo as (a int, b int, x int, y int):
SELECT *
FROM json_populate_record(null::other_foo, '{"a":1,"b":2,"c":3,"d":4}');
Run Code Online (Sandbox Code Playgroud)
返回:
SELECT *
FROM json_populate_record(null::foo, '{"a":1,"b":2,"c":3,"d":4}')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1173 次 |
最近记录: |