如何在 PostgreSQL 9.5 中获取特定模式中所有表的行数统计?

5
如何在PostgreSQL 9.5中获取特定模式中所有表的行数?我希望结果以表名 | 行数的形式呈现。请问如何使用查询实现此功能?
2个回答

14

这可以通过一些XML魔法来实现:

select table_schema, table_name,
       (xpath('/row/count/text()', query_to_xml('select count(*) from '||format('%I.%I', table_schema, table_name), true, true, '')))[1]::text::int as row_count
from information_schema.tables
where table_schema = 'public'

10

https://www.postgresql.org/docs/current/static/monitoring-stats.html

n_live_tup 估计的活动行数

t=# select relname,n_live_tup 
from pg_stat_all_tables 
where schemaname = 'public' 
order by n_live_tup desc 
limit 3;
        relname       | n_live_tup
------------+---------------------+------------
  x_pricing           |   96493977
  x_forum             |   57696510
  x_uploading         |   55477043
(3 rows)

当然,这些数据都只是近似值。如果要计算精确数字,您需要使用动态plpgsql(顺便说一下,这将为您提供更接近的数字,但仍然只是近似值)。这两种近似值取决于您更改数据和运行vacuum的频率...
这种方法的好处当然是消耗更少的资源(负载和时间)。使用count(*)的好处是以服务器负载和等待时间为代价获得更精确的结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接