我正在做一个项目,在该项目中对 postgres 数据库中的某些表进行计算,并且在代码的不同部分,进行了 2 种不同的计算:
select pg_total_relation_size ('TABLENAME');
Run Code Online (Sandbox Code Playgroud)
第二个:
select (relpages*8/1024) from pg_class where relname='TABLENAME' (Size in MB)
Run Code Online (Sandbox Code Playgroud)
我知道 pg_total_relation_size 是我需要使用的,但我想知道这个其他计算代表什么,如果第二个也是某种大小计算,为什么我对同一个表得到不同的结果?
您可以使用pg_size_pretty(pg_total_relation_side(oid))漂亮的打印表格大小:
select nspname
, relname
, pg_size_pretty(pg_total_relation_size(c.oid)) as "size"
from pg_class c
left join
pg_namespace n
on n.oid = c.relnamespace
where nspname not in ('pg_catalog', 'information_schema')
order by
pg_relation_size(c.oid) desc;
Run Code Online (Sandbox Code Playgroud)
pg_total_relation_size- 是查看完整表大小的正确方法,因为它包括索引和TOAST数据使用的磁盘空间。
当您执行第二个选择时 - 您仅获得表大小(relpages是以 8Kb 页为单位的表大小)。您也可以从pg_class获取 TOAST 和索引大小,但您需要按照此处所述执行更多 sql 查询,并对您获得的所有大小求和。