在循环由2个子查询的结果组成的记录时访问列

时间:2017-03-02 16:59:10

标签: postgresql

我有一个代码块,我在其中循环包含两个连接子查询的记录,这些子查询在不同的表中包含同样命名的列。

现在我似乎能够访问记录中的sq1和sq2,但不能访问内容,而且我总是得到"无法识别列' c1'在记录数据类型"中,即使我向列添加显式别名:

DO $$
DECLARE
    r record;
BEGIN
    FOR r IN SELECT sq1, sq2
        FROM (SELECT t1.someColumn as c1, t2.someColumn as c2, ... FROM Table1 t1 JOIN Table2 t2 ...) sq1
        JOIN (SELECT t1.someColumn as c1, t2.someColumn as c2, ... FROM Table1 t1 JOIN Table2 t2 ...) sq2
        ON (sq1.joinColumn1 = sq2.joinColumn2 AND sq1.joinColumn2 = sq2.joinColumn1)
    LOOP
        INSERT INTO Table3 (column1, column2)
        VALUES ((r.sq1).c1, (r.sq2).c1);
               --^ error occurs here
    END LOOP;
END$$;

我正在寻找一种方法来访问类似于以下方式的记录:

r.sq1.t1.someColumn

1 个答案:

答案 0 :(得分:1)

要访问变量中的3级,必须将其强制转换为命名记录类型。它可能是表格或类型:

对于类型:

CREATE TYPE my_type AS (c1 int4, c2 int4, joinColumn1 int4);

表格:

CREATE TABLE my_type (c1 int4, c2 int4, joinColumn1 int4);

之后你可以这样做:

DO $$

DECLARE
    r record;
BEGIN
    FOR r IN SELECT (sq1.*)::my_type AS sq1, (sq2.*)::my_type AS sq2
        FROM (SELECT 10 as c1, 11 as c2, 1 as joinColumn1) sq1
        JOIN (SELECT 20 as c1, 21 as c2, 1 as joinColumn2) sq2
        ON (sq1.joinColumn1 = sq2.joinColumn2)
    LOOP
          RAISE NOTICE '%', r;
          RAISE NOTICE '%', r.sq1;
          RAISE NOTICE '% %', (r.sq1).c1, (r.sq2).c1;
          INSERT INTO Table3 (column1, column2)
          VALUES ((r.sq1).c1, (r.sq2).c1);
    END LOOP;
END$$;