访问记录成员

时间:2014-09-26 16:23:58

标签: sql postgresql postgresql-9.1

根据each()的文档,它会返回setof(key text, value text)。但是,从SELECT使用时,我似乎无法访问keyvalue。我已尝试搜索有关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)
...

如果我尝试访问keyvalue,我会收到各种错误。

  1. 此:

    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
    
  2. 此:

    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
    
  3. 此:

    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
    
  4. 此:

    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
    
  5. 如何在PostgreSQL中正确访问record类型的成员?

1 个答案:

答案 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)

我之所以提到这一点是因为返回recordsetof record 而没有类型OUT参数的函数无法按照我上面所示的方式使用,你必须为这些函数提供一个特殊的格式参数列表。