根据each()
的文档,它会返回setof(key text, value text)
。但是,从SELECT
使用时,我似乎无法访问key
或value
。我已尝试搜索有关record
类型的信息,但我发现的所有信息都与plpgsql无关。
说我有下表:
CREATE TABLE mytable (
id SERIAL NOT NULL PRIMARY KEY,
data HSTORE NOT NULL
);
我运行查询:
SELECT pair
FROM (
SELECT each(data) AS pair
FROM mytable
) AS pairs
我获得了record
类型的行:
(key1,value1)
(key2,value2)
...
如果我尝试访问key
或value
,我会收到各种错误。
此:
SELECT pair.key, pair.value
FROM (
SELECT each(data) AS pair
FROM mytable
) AS pairs
给出:
ERROR: missing FROM-clause entry for table "pair"
LINE 1: pair.key,
^
********** Error **********
ERROR: missing FROM-clause entry for table "pair"
SQL state: 42P01
Character: 8
此:
SELECT pair.key, pair.value
FROM (
SELECT each(data) AS pair (key, value)
FROM mytable
) AS pairs
给出:
ERROR: syntax error at or near "("
LINE 4: each(attributes) AS pair (key, value)
^
********** Error **********
ERROR: syntax error at or near "("
SQL state: 42601
Character: 71
此:
SELECT pairs.pair.key, pairs.pair.value
FROM (
SELECT each(data) AS pair
FROM mytable
) AS pairs
给出:
ERROR: schema "pairs" does not exist
********** Error **********
ERROR: schema "pairs" does not exist
SQL state: 3F000
此:
SELECT pair[1], pair[2]
FROM (
SELECT each(data) AS pair
FROM mytable
) AS pairs
给出:
ERROR: cannot subscript type record because it is not an array
********** Error **********
ERROR: cannot subscript type record because it is not an array
SQL state: 42804
如何在PostgreSQL中正确访问record
类型的成员?
答案 0 :(得分:3)
在PostgreSQL 9.3中,使用LATERAL
。
regress=> SELECT p.key, p.value FROM mytable, LATERAL each(data) p;
key | value
-----+-------
a | b
c | d
(2 rows)
在旧版本中,您必须使用通配符扩展,这有点难看。
regress=> SELECT (pair).*
FROM (
SELECT each(data) AS pair
FROM mytable
) AS pairs
;
key | value
-----+-------
a | b
c | d
(2 rows)
旁注:
each
返回带有OUT
参数的类型化结果集,因此返回类型和列名称是已知的。它返回一个集合,即它可以为单个调用返回多行:
regress=> \df each
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+-----------------------------------------+--------
public | each | SETOF record | hs hstore, OUT key text, OUT value text | normal
(1 row)
我之所以提到这一点是因为返回record
或setof record
而没有类型OUT
参数的函数无法按照我上面所示的方式使用,你必须为这些函数提供一个特殊的格式参数列表。