【问题标题】:How to add data from table to biggest object query in PostgreSQL如何将数据从表添加到 PostgreSQL 中的最大对象查询
【发布时间】:2015-06-28 20:19:49
【问题描述】:

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 postgresql


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多