如何在postgresql中的单个函数中编写多个查询

时间:2015-07-16 12:48:18

标签: sql postgresql function

我需要在Postgresql中编写一个函数,该函数将返回一个包含三列的表。这三列将从三个不同的查询中填充。 我想知道如何在一个功能中加入这三个查询。

CREATE OR REPLACE FUNCTION ytd(MMYY character varying, MMYY1 character varying)
  RETURNS TABLE(name character varying, ratio bigint, ratio1 bigint) AS
$BODY$

BEGIN
RETURN query
SELECT col1 as name from t1, 
Select col2 as ratio from t2,
Select col3 as ratio1 from t3


END
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;
ALTER FUNCTION ydt2(MMYY character varying, MMYY1 character varying)
  OWNER TO postgres;

每个sql中都会传递相同的参数

1 个答案:

答案 0 :(得分:1)

如果你JOIN三个数据集的方法无关紧要(正如你所说的那样无关),那么合并这三个数据集应该是非常简单的(参见SQL Fiddle

这个SQL(下面)应举例说明:

CREATE TABLE a (a1 INTEGER);
CREATE TABLE b (b1 INTEGER);
CREATE TABLE c (c1 INTEGER);

INSERT INTO a VALUES(11), (12);
INSERT INTO b VALUES(21), (22);
INSERT INTO c VALUES(31), (32);

WITH 
  aa AS (SELECT row_number() OVER () AS r, * FROM a),
  bb AS (SELECT row_number() OVER () AS r, * FROM b),
  cc AS (SELECT row_number() OVER () AS r, * FROM c)
SELECT r, a1, b1, c1
FROM aa
  JOIN bb
    USING (r)
  JOIN cc
    USING (r)