Postgresql
使用類型代替列定義列表?
執行下面,我得到*“a column definition list is required for functions return “record”"*。
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}');
沒關係。我知道它想要什麼。
SELECT * FROM json_to_record('{"a":1,"b":2,"c":3,"d":4}') AS (a int, b int, c int, d int);
此外,在 PostgreSQL 中,所有表都已經具有由相同名稱創建的類型。
CREATE TABLE foo(a,b,c,d) AS VALUES (1,2,3,4);
foo
這將創建一個連結到新創建的表的內部類型foo
。不過,我可以很容易地創建一個類似的類型bar
。CREATE TYPE bar AS (a int, b int, c int, d int);
能夠將返回的記錄投射
json_to_record()
到 bar 那就太好了。SELECT * FROM json_to_record('{"a":1,"b":2,"c":3,"d":4}') AS foo; -- bar? anything?
無論如何要滿足具有類型的列定義列表嗎?
使用
json_populate_record
:SELECT * FROM json_populate_record(null::foo, '{"a":1,"b":2,"c":3,"d":4}')
列匹配是按名稱完成的,不存在的列會被忽略:
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}');
返回:
a | b --+-- 1 | 2