代码之家  ›  专栏  ›  技术社区  ›  user3.1415927

Postgresql-我可以使用一个表加上另一个表中的一列的返回类型吗?

  •  0
  • user3.1415927  · 技术社区  · 7 年前

    我有一个PostgreSQL函数,返回 table1 id 属于 table2 . 我不希望为新的返回类型键入每个字段(如图所示) here RETURNS TABLE 例如),因为这个表中有九列,我将针对不同的类似查询多次这样做。(该查询是一个 INNER JOIN .)

    我想做一些类似的事情:

    ...
    RETURNS SETOF schema.table1 || schema.table2.id
    ...
    $$
    etc
    $$
    

    有没有一种简单的方法可以通过表名/类型来实现这一点,或者我必须键入每一列并再次键入?

    0 回复  |  直到 7 年前
        1
  •  2
  •   Laurenz Albe    7 年前

    通过如下定义函数返回类型,可以轻松实现这一点:

    RETURNS TABLE (
       t1    schema.table1,
       t2_id bigint
    )
    

    然后在结果集中只会得到两列,但第一列是对应于的复合类型 table1

    SELECT (t1).*, t2_id FROM func();
    
        2
  •  0
  •   Pavel Stehule    7 年前

    你可以使用 table inheritance :

    postgres=# create table t1(a int, b int);
    CREATE TABLE
    
    postgres=# create table t2(c int) inherits(t1);
    CREATE TABLE
    postgres=# \d t2
                      Table "public.t2"
    +--------+---------+-----------+----------+---------+
    | Column |  Type   | Collation | Nullable | Default |
    +--------+---------+-----------+----------+---------+
    | a      | integer |           |          |         |
    | b      | integer |           |          |         |
    | c      | integer |           |          |         |
    +--------+---------+-----------+----------+---------+
    Inherits: t1