gpt4 book ai didi

sql - 如何将表中的数据添加到 PostgreSQL 中的最大对象查询

转载 作者:行者123 更新时间:2023-11-29 13:27:33 26 4
gpt4 key购买 nike

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 以外的模式返回表。在这种情况下,公司名称列应为空或 null。

最佳答案

这对于普通 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;

关于sql - 如何将表中的数据添加到 PostgreSQL 中的最大对象查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097997/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com