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

Kar*_*hik 3 sql postgresql postgresql-9.5

如何获取PostgreSQL 9.5中特定模式中存在的所有表的表行计数?我想将结果作为table_name | row_count。如何使用查询完成此操作?

Vao*_*sun 6

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)
Run Code Online (Sandbox Code Playgroud)

当然,该数据将达到某种近似水平。要计算确切的数字,您将需要动态的plpgsql(顺便说一句,它会为您提供更接近的数字,但仍会达到近似值)。两种近似值都取决于您更改数据和运行真空的频率...

这种方法的好处当然是更少的资源消耗(负载和时间)。count(*)的好处是以服务器负载和等待时间为代价的更精确的结果


a_h*_*ame 6

这可以通过一些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'
Run Code Online (Sandbox Code Playgroud)