简体   繁体   English

PostgreSQL:在FROM子句中调用函数不止一次

[英]PostgreSQL: Call a Function More Than Once in FROM Clause

How can I call a function which returns records more than once in FROM clause? 如何在FROM子句中调用一个返回记录多次的函数? I understand that I have to specify a 'column definition list' when using a function that returns records. 我了解使用返回记录的函数时,必须指定“列定义列表”。 But how can I then use aliases for that function? 但是我该如何使用别名呢?

Example: 例:

CREATE OR REPLACE FUNCTION foo(which_foo int) RETURNS SETOF RECORD AS
$BODY$BEGIN
IF which_foo=0 THEN
 RETURN QUERY EXECUTE 'SELECT 1::int,2::int;';
ELSE 
 RETURN QUERY EXECUTE 'SELECT 1::int,2::int;';
END IF;
END$BODY$
LANGUAGE plpgsql;

SELECT * FROM foo(0) AS (a int, b int);;
SELECT * FROM foo(1) AS (c int, d int);
SELECT * FROM foo(0) AS (a int, b int), foo(1) AS (c int, d int);

The last select statement will fail with: 最后一个选择语句将失败,并显示:

ERROR:  table name "foo" specified more than once

I want to keep using the column definition list, because the function I want to use in the end has to be as generic as possible. 我想继续使用列定义列表,因为最后要使用的函数必须尽可能通用。

SELECT f0.*, f1.*
FROM
    foo(0) AS f0 (a int, b int),
    foo(1) AS f1 (c int, d int);

I understand that I have to specify a 'column definition list' when using a function that returns records. 我了解使用返回记录的函数时,必须指定“列定义列表”。

No, you do not. 你不可以。 I wouldn't operate with anonymous records. 我不会处理匿名记录。 Declare the return type , since you already know it: 声明返回类型 ,因为您已经知道它:

CREATE OR REPLACE FUNCTION foo(which_foo int)
 RETURNS TABLE (a int, b int) AS
$func$
BEGIN
    IF which_foo = 0 THEN
        RETURN QUERY SELECT 1,2;
    ELSE 
        RETURN QUERY SELECT 1,2;
    END IF;
END
$func$ LANGUAGE plpgsql;

And assuming you do not want to combine multiple calls into one row, you should use UNION ALL : 并假设您不想将多个调用合并为一行,则应使用UNION ALL

SELECT * FROM foo(0)
UNION ALL
SELECT * FROM foo(1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM