【问题标题】:How to loop over list of schemas in POSTGRESQL如何遍历 POSTGRESQL 中的模式列表
【发布时间】:2018-03-07 10:38:54
【问题描述】:

我可以访问具有许多模式的 db(每个模式 - 单独的存储)。而且这个分贝还没有information_schema

下一个代码给了我一个超过 1K 模式的列表:

SELECT nspname FROM pg_namespace WHERE nspname LIKE 'cabinet%'

我需要为该列表中的每个方案计算某个表中的行数(如果存在)。比如:

for scheme in scheme_list:
    SELECT scheme, count(*) FROM scheme.table_i_need

输出应包含 schema_name 和一些整数值。

这么久了还是没找到答案,请大家帮忙。

UPD:感谢Vao Tsun,我什至能够在带有架构名称的文本数组上编写这个循环。

do $$
    declare
    m text[];
    a text[] := array[['cabinet1003052234'], ['cabinet1027326445'], ['cabinet1062828216'], ['cabinet108034857']];
    s text;
begin
FOREACH m SLICE 1 IN ARRAY a LOOP
execute format('select count(*) from %I.react_order', CAST (m[1] AS regnamespace)) into s;
    raise info '%: %', m,s;
end loop;
end;
$$
;

【问题讨论】:

标签: postgresql database-schema


【解决方案1】:

您的方法会更加昂贵 - 列出模式,然后检查表是否存在,然后计算行数。你要么依赖来自pg_stat_* 的统计数据,要么依赖来自 pg_class 的循环计数,比如:

t=# do $$
declare
 r record;
 s text;
begin
for r in (select relnamespace::regnamespace nspname,relname from pg_class where relname like 't%' and relkind = 'r') loop
 execute format('select count(*) from %I.%I',r.nspname,r.relname) into s;
 raise info '%.%: %', r.nspname,r.relname, s;
end loop;
end;
$$
;
INFO:  postgres.tb: 1
INFO:  postgres.tt: 0
INFO:  public.tt: 0
INFO:  postgres.t3: 1
INFO:  postgres.testtable: 1
INFO:  a.tt: 0
INFO:  b.tt: 0
INFO:  postgres.tT: 0
INFO:  postgres.ta: 1
INFO:  postgres.t5: 1
INFO:  postgres.tb1: 1
INFO:  postgres.tb2: 1
INFO:  s1.t: 1
INFO:  s2.t: 1
INFO:  postgres.test: 1
INFO:  public.test: 6
INFO:  postgres.t: 9904
DO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    相关资源
    最近更新 更多