分离postgres函数返回的记录

时间:2009-12-11 04:10:05

标签: sql postgresql

我有一个函数通过output parameters将两个参数作为匿名复合类型返回。

我可以使用如下查询访问各个列:

# select * from guess_user('Joe','Bloggs');
 confidence | matchid 
------------+---------
   0.142857 |    1121

现在我想将此函数的输出与一些数据结合起来:

# select firstname,lastname from users limit 5;
 firstname | lastname 
-----------+----------
 Adam      | Smith
 Amy       | Peters
 Annette   | Bloggs
 Annie     | Mills
 Amanda    | Hibbins

我正在寻找一个输出以下内容的查询:

 firstname | lastname | confidence | matchid 
-----------+----------+------------+---------
 Adam      | Smith    |            | 
 Amy       | Peters   |            | 
 Annette   | Bloggs   |            | 
 Annie     | Mills    |            | 
 Amanda    | Hibbins  |            | 

使用调用guess_user的结果填充置信度和匹配列,并使用该行中的名称。

我目前最近的努力是:

# select firstname, lastname, guess_user(firstname, lastname) from users limit 5;

返回:

 firstname | lastname  |  guess_user   
-----------+-----------+---------------
 Angela    | Abbott    | (0.285714,3)
 Amy       | Allan     | (0.285714,4)
 Annette   | Allison   | (0.285714,5)
 Annie     | Ashworth  | (0.285714,6)
 Amanda    | Baird     | (0.285714,7)

有没有办法将guess_user输出拆分成单独的列?

5 个答案:

答案 0 :(得分:10)

结合depesz和fazal的答案,这似乎有效:

select firstname, lastname, (guess_user(firstname, lastname)).*
from users
limit 5

答案 1 :(得分:2)

简单地说就是这样:

select firstname, lastname, x.confidence, x.matchid
from 
(
select firstname, lastname, guess_user(firstname, lastname) as x
from users
limit 5
) q;

答案 2 :(得分:1)

您需要更改功能to return a set - 最后一个示例与您要求的功能相同。

答案 3 :(得分:0)

除非有人出现并纠正我,否则我认为答案是8.3目前无法实现,但可以在Postgres 8.4中完成。

http://www.depesz.com/index.php/2008/11/03/waiting-for-84-pl-srf-functions-in-selects/

答案 4 :(得分:0)

您可能需要在depesz的解决方案中对“x”进行括号,以便将复合记录值与表区分开来,因此您不会收到消息:

missing FROM-clause entry for table "x"

至少我在9.0.2上做过。

相关问题