【问题标题】:how to iterate in all schemas and find count from all tables present in all schemas with same table name for every 5mins?如何在所有模式中迭代并每 5 分钟从具有相同表名的所有模式中的所有表中查找计数?
【发布时间】:2022-07-29 12:54:55
【问题描述】:

想象一下我的数据库中有 5 个模式,并且在每 5 分钟记录插入 table1 后,每个模式都有一个通用名称表(例如:-table1),我如何在所有模式中迭代 n 计算 table1 的计数 [我必须自动化这个过程,所以我要在函数中编写代码,并在每 5 分钟后使用 crontab 调用该函数]。

【问题讨论】:

  • SELECT (SELECT count(*) FROM schema1.table1) AS schema1count, (SELECT count(*) FROM schema2.table1) AS schema2count, (SELECT count(*) FROM schema3.table1) AS schema3count, …;

标签: postgresql


【解决方案1】:

基本上 2 个选项:硬编码 schema.table 并合并结果。所以像:

create or replace function count_rows_in_each_table1()
  returns table (schema_name text, number_or_rows integer) 
  language sql 
as $$
    select 'schema1', count(*) from schema1.table1 union all 
    select 'schema2', count(*) from schema2.table1 union all
    select 'schema3', count(*) from schema1.table1 union all
    ...
    select 'scheman', count(*) from schema3.table1; 
$$;

另一种方法是从 information_scheme 动态构建查询。

create or replace function count_rows_in_each_table1()
  returns table (schema_name text, number_of_rows bigint) 
 language plpgsql
as $$
declare
     c_rows_count  cursor  is
        select table_schema::text 
          from information_schema.tables
          where table_name = 'table1';
      
    l_tbl           record; 
    l_sql_statement text = ''; 
    l_connector     text = '';
    l_base_select   text = 'select ''%s'', count(*) from %I.table1'; 

begin
 
     for l_tbl in c_rows_count
     loop  
         l_sql_statement = l_sql_statement ||
                           l_connector ||  
                           format (l_base_select, l_tbl.table_schema, l_tbl.table_schema);
         l_connector = ' union all '; 
     end loop; 

     raise notice E'Running Query: \n%', l_sql_statement; 
     return query execute l_sql_statement; 
end;
$$; 

哪个更好。使用很少的模式和很少的模式添加/删除,选择第一个。它直接且轻松地显示您在做什么。如果您经常添加/删除架构,则选择第二个。如果您有很多架构,但很少添加/删除它们,则修改第二个以生成第一个,保存并安排执行生成的查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2021-04-13
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多