[英]PL/pgSQL: Add static column to query result
I have this function: 我有这个功能:
CREATE OR REPLACE FUNCTION func2(a integer[])
RETURNS SETOF newset AS
$BODY$
declare
x int;
begin
FOREACH x IN ARRAY $1
LOOP
RETURN QUERY SELECT * FROM func1(x);
END LOOP;
return;
end;
$BODY$
LANGUAGE plpgsql VOLATILE
func2
simply append all rows from all calls to func1
. func2
只需将所有调用的所有行附加到func1
。 if first call to func1
gave 2 rows and second call gave 3 rows, func2
will return in total 5 rows (the rows themselves). 如果第一次调用
func1
给了2行,第二次调用给了3行,则func2
将总共返回5行(这些行本身)。
func1
returns a schema of 3 columns so currently func2
return same schema. func1
返回3列的架构,因此当前func2
返回相同的架构。
I want to change func2
so it will return 4 columns. 我想更改
func2
因此它将返回4列。 the 3 from func1
and another column which contains the value of x
. 来自
func1
的3和另一个包含x
值的列。
for example: calling func2(ARRAY[500,200])
and assume func1(500)
return 2 rows and func1(200)
return 3 rows. 例如:调用
func2(ARRAY[500,200])
并假定func1(500)
返回2行,而func1(200)
返回3行。 I will get: 我会得到:
first second third forth
a b c 500
d e f 500
g h i 200
j k l 200
m n o 200
I created a newset2
which is newset
with another column of int for func2 我创建了一个
newset2
,它是newset
与func2的int的另一列
CREATE OR REPLACE FUNCTION func2(a integer[])
RETURNS SETOF newset2 AS
How do I add the desired column to the function? 如何将所需的列添加到函数?
您可以返回额外的列:
RETURN QUERY SELECT *, x FROM func1(x);
This can be substantially more efficient with a plain SELECT
query using unnest()
a LATERAL
join. 使用使用
unnest()
和LATERAL
unnest()
的普通SELECT
查询,这可以大大提高效率 。 Applying any sort order is simpler, too. 应用任何排序顺序也更简单。
SELECT f.*, x
FROM unnest(ARRAY[500,200]) x, func1(x) f -- implicit LATERAL join
ORDER BY x;
That's all, including the additionally requested sort order. 仅此而已,包括另外要求的排序顺序。
It's a drop-in replacement for your SELECT * FROM func2(ARRAY[500,200])
, no func2()
needed. 它是
SELECT * FROM func2(ARRAY[500,200])
替代品,不需要func2()
。
You can still wrap this into a function, of course. 当然,您仍然可以将其包装为一个函数。 I suggest a simple SQL function:
我建议一个简单的SQL函数:
CREATE OR REPLACE FUNCTION func2(a integer[])
RETURNS SETOF newset AS
$func$
SELECT f.*, x
FROM unnest(ARRAY[500,200]) x, func1(x) f
ORDER BY x;
$func$ LANGUAGE sql
The row type newset
has to be pre-defined somehow. 行类型
newset
必须以某种方式预先定义。
Related: 有关:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.