Postgres 9.1+数据库包含每个名为firma
的公司和公司编号的不同架构,如firma1, firma5, firma99, firma12
。
每个架构都包含一个公司名称为
的表-- this table contains always exactly one row:
create table firma5.company ( company char(50) not null );
以下查询列出了最大的对象:
select
(n.nspname||'.'||relname)::char(45) as tablename
, pg_size_pretty(pg_total_relation_size(c.oid))::char(10) as totalsize
, case
when c.relkind='i' then 'index'
when c.relkind='t' then 'toast'
when c.relkind='r' then 'table'
when c.relkind='v' then 'view'
when c.relkind='c' then 'composite type'
when c.relkind='S' then 'sequence'
else c.relkind::text
end ::char(14) as "type"
from
pg_class c
left join pg_namespace n on n.oid = c.relnamespace
left join pg_tablespace t on t.oid = c.reltablespace
where
(pg_total_relation_size(c.oid)>>20)>0 and c.relkind!='t'
order by
pg_total_relation_size(c.oid) desc
此查询显示公司模式,如firma1,firma5等。
如何在此查询结果中显示公司名称(firman.company.company
)?查询还可以返回除firmaN之外的模式中的表。在这种情况下,公司名称列应为空或为空。
答案 0 :(得分:1)
使用纯SQL无法做到这一点,因为您无法事先指定要加入的表名,因此您需要运行动态查询。但是,如果模式具有公司表,则可以创建一个从动态查询返回公司名称的简单函数:
CREATE FUNCTION company_name (sch text) RETURNS text AS $$
DECLARE
comp text := NULL;
BEGIN
IF strpos(sch, 'firma') = 1 THEN
EXECUTE 'SELECT company FROM ' || sch || '.company' INTO comp;
END IF;
RETURN comp;
END; $$ LANGUAGE plpgsql STRICT STABLE;
然后在查询中使用该函数:
select
(n.nspname||'.'||c.relname)::char(45) as tablename
, pg_size_pretty(pg_total_relation_size(c.oid))::char(10) as totalsize
, case
when c.relkind='i' then 'index'
-- when c.relkind='t' then 'toast' FILTERED OUT IN WHERE CLAUSE
when c.relkind='r' then 'table'
when c.relkind='v' then 'view'
when c.relkind='c' then 'composite type'
when c.relkind='S' then 'sequence'
else c.relkind::text
end ::char(14) as "type"
, company_name(n.nspname) as company -- <<<<<<<<<<<<<<<<<<<<<<<
from pg_class c
left join pg_namespace n on n.oid = c.relnamespace
--left join pg_tablespace t on t.oid = c.reltablespace NOT USED
where (pg_total_relation_size(c.oid)>>20)>0 and c.relkind!='t'
order by pg_total_relation_size(c.oid) desc;