PostgreSQL - 结合查询

时间:2018-02-27 12:02:08

标签: postgresql select

我有一个查询,我想与另一个查询结合但没有成功。

第一个查询返回所有具有名为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的所有值?

提前致谢,Doobie

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

如果方案数量未知,则无法为一般问题创建单个查询。但是您可以为此创建存储过程。我认为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();