如何获取特定模式

时间:2016-05-26 09:42:05

标签: greenplum hawq

我们有基于Postgres的只读数据库。其中,我们在一个模式下有52个表。

我们正在尝试为一个模式下的所有表输出行计数和最大值(时间戳)列。

环境是:

PostGLSQL 8.2.15(Greenplum Database 4.2.0 build 1)(HAWQ 1.3.0.2 build 14421)在x86_64-unknown-linux-gnu上,由GCC gcc(GCC)4.4.2编译编译

我们尝试过:

SELECT 
  nspname AS schemaname,relname,reltuples,max(time)
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE 
  nspname NOT IN ('pg_catalog', 'information_schema') AND
  relkind='r' 
ORDER BY reltuples DESC;

在此查询中,我们获得了行计数列,但仍未达到所有表的最大值(时间戳)。

对此有任何帮助将不胜感激?

2 个答案:

答案 0 :(得分:4)

您使用此查询访问的是数据库统计信息,这不是100%准确,可能会丢失或过时,具体取决于您的统计信息收集过程。

要获取表列表的行数,您必须扫描每个表。但是,您可以使用pg_relation_size()来了解表格大小(以字节为单位),此功能不需要您扫描表格。

如果您的表格列表是静态的,您可以使用以下查询:

select 'table1', count(*), max(time) from table1
union all
select 'table2', count(*), max(time) from table2
union all
...
select 'table52', count(*), max(time) from table52;

此解决方案不灵活,就像表列表已更改一样,您需要重写查询。

第二个选项是生成此查询并手动执行它:

select string_agg(query, ' union all ') as query
    from (
        select 'select ''' || n.nspname || '.' || c.relname || ''', count(*), max(time) from ' || n.nspname || '.' || c.relname as query
            from pg_namespace as n, pg_class as c
            where n.oid = c.relnamespace
                and n.nspname = 'my_schema'
        ) as q;

这更灵活,但第二个查询应该手动执行。

最后你的最后一个选择 - 编写一个函数:

create or replace function table_sizes (schemaname varchar) returns setof record as $BODY$
declare
    r record;
    t varchar;
begin
    for t in execute $$
        select n.nspname || '.' || c.relname
            from pg_namespace as n, pg_class as c
            where n.oid = c.relnamespace
                and c.relkind = 'r'
                and n.nspname = '$$ || schemaname || $$'$$
    loop
        execute 'select ''' || t || '''::varchar, count(*), max(time) from ' || t
            into r;
        return next r;
    end loop;
    return;
end;
$BODY$ language plpgsql volatile;

select * from table_sizes('public') t(tablename varchar, rowcount bigint, maxtime time);

答案 1 :(得分:1)

以下是其他一些步骤:

在psql中执行以下步骤

\o count_per_schema.sql
select 'select count(*)as '||c.relname||', max(time) from ' || n.nspname || '.' || c.relname || ';' as " " from pg_namespace as n, pg_class as c where n.oid = c.relnamespace and c.relkind='r' and n.nspname = 'schema_name';
\o
\i count_per_schema.sql

\o会将结果重定向到您提供的filename。例如,count_per_schema.sql\i将运行文件中的所有查询。

这是我在服务器上所做的。我没有选择max(时间)。

yogesh=# \o count_per_schema.sql
yogesh=# select 'select count(*)as '||c.relname||' from ' || n.nspname || '.' || c.relname || ';' as " " from pg_namespace as n, pg_class as c where n.oid = c.relnamespace and c.relkind='r' and n.nspname = 'public';
yogesh=# \o
yogesh=# \i count_per_schema.sql

 heap1
-------
 20000
(1 row)
 test
-------
     4
(1 row)
 users
-------
     0
(1 row)
 skew_demo
-------
 10609
(1 row)