【问题标题】:PostgreSQL - Combine QueriesPostgreSQL - 组合查询
【发布时间】:2018-02-28 14:33:37
【问题描述】:

我有一个查询要与另一个查询合并,但没有成功。

第一个查询返回表名为status 的所有模式名称:

select s.schema_name 
from   information_schema.schemata s 
where exists (select * 
              from information_schema.tables t 
              where t.table_schema = s.schema_name 
              and t.table_name = 'status')

在每个状态表中有一个列lastLogin,可以这样选择:

select "lastLogin" 
from   "someID".status 
where  "lastLogin" is not null

如何从每个模式的所有状态表中获取 lastLogin 的所有值?

提前致谢,杜比

【问题讨论】:

    标签: postgresql select


    【解决方案1】:

    您不能这样做,因为 SQL 查询中的模式名称必须是一个常量值。您必须根据第一个查询的结果构造第二个查询。

    您可以做的是构造第二个查询,以便它使用 UNION 在单个查询中查询 所有 个名为 status 的表。

    【讨论】:

    • 感谢 Albe 先生的回答和专业知识!
    【解决方案2】:

    对于方案数量未知的一般问题,您无法创建单个查询。但是您可以为此创建一个存储过程。我假设lastLogin 的类型为TIMESTAMP

    CREATE FUNCTION list_last_logins() RETURNS SETOF TIMESTAMP AS $$
    DECLARE
        the_row RECORD;
        the_statement TEXT;
        the_result RECORD;
    BEGIN
        FOR the_row IN SELECT t.schema_name FROM information_schema.tables t WHERE t.table_name = 'status'
        LOOP
            the_statement := FORMAT('SELECT "lastLogin" FROM %s.status WHERE "lastLogin" IS NOT NULL', the_row.schema_name);
            FOR the_result IN EXECUTE the_statement
            LOOP
                RETURN the_result."lastLogin";
            END LOOP;
        END LOOP;
        RETURN;
    END;
    $_$ LANGUAGE plpgsql;
    

    从 Postgres 9.5 开始,内部循环可以缩短为:

    CREATE FUNCTION list_last_logins() RETURNS SETOF TIMESTAMP AS $$
    DECLARE
        the_row RECORD;
        the_statement TEXT;
    BEGIN
        FOR the_row IN SELECT t.schema_name FROM information_schema.tables t WHERE t.table_name = 'status'
        LOOP
            the_statement := FORMAT('SELECT "lastLogin" FROM %s.status WHERE "lastLogin" IS NOT NULL', the_row.schema_name);
            RETURN QUERY EXECUTE the_statement;
        END LOOP;
        RETURN;
    END;
    $_$ LANGUAGE plpgsql;
    

    您现在可以选择所有值

    SELECT * FROM list_last_logins();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      相关资源
      最近更新 更多