当前位置:   article > 正文

Postgresql 表结构、列名相关信息查询_postgresql 查询一个表的列名 主键和非主键分组

postgresql 查询一个表的列名 主键和非主键分组

查询数据库拥有的表数量

  1. select count(*)
  2. from pg_class c join pg_namespace n on relnamespace = n.oid where relkind = 'r' and n.nspname = 'public' ;

查询所有表名及注释

  1. -- 方法一
  2. select relname, reltuples as rw,obj_description(c.oid)
  3. from pg_class c join pg_namespace n on relnamespace = n.oid where relkind = 'r' and n.nspname = 'public';
  4. -- 方法二 加条件 and relchecks=0是过滤掉分表
  5. SELECT relname as tabname,
  6. cast(obj_description(relfilenode,'pg_class') as varchar) as comment
  7. FROM pg_class c 
  8. WHERE relchecks=0
  9. AND relkind = 'r'
  10. AND relname not like 'pg_%'
  11. AND relname not like 'sql_%'
  12. order by relname;

查询字段名、类型、注释、是否为空

  1. SELECT
  2. col_description(a.attrelid,a.attnum) as comment,
  3. format_type(a.atttypid,a.atttypmod) as type,
  4. a.attname as name,
  5. a.attnotnull as notnull
  6. FROM pg_class as c,pg_attribute as a
  7. where c.relname = '表名'
  8. and a.attrelid = c.oid
  9. and a.attnum>0;

查询表字段(详细版):列名、备注、类型、是否为空、长度、是否为主键

  1. select a.attname as colname, col_description(a.attrelid,a.attnum) as remarks,t.typname,a.attnotnull as notnull ,
  2. (case when atttypmod-4>0 then atttypmod-4 else 0 end) len,
  3. (case when (select count(*) from pg_constraint where conrelid = a.attrelid and conkey[1]=attnum and contype='p')>0
  4. then 'Y' else 'N' end) as primarykey
  5. from pg_attribute a left join pg_class c on a.attrelid = c.oid
  6. left join pg_type t on a.atttypid = t.oid
  7. where a.attnum >= 0 and c.relname = '表名'
  8. order by c.relname desc, a.attnum asc

查询表和表字段(表名和列的详细信息的融合)

  1. select ROW_NUMBER() over(ORDER bY c.relname , a.attnum asc ) AS num,
  2. c.relname as 英文表名,
  3. de.description as 中文表名,
  4. a.attname as 英文字段名称,
  5. col_description(a.attrelid,a.attnum) as 中文字段名称,
  6. t.typname 字段类型,
  7. (case when atttypmod-4>0 then atttypmod-4 else 0 end) 字段长度,
  8. '0' 字段小数位数,
  9. (case when a.attnotnull='t' THEN '是' ELSE '否' END ) 字段是否非空,
  10. (case when (select count(*) from pg_constraint where conrelid = a.attrelid
  11. and conkey[1]=attnum and contype='p')>0 then '是' else '否' end) 字段是否主键,
  12. '该字段为'||col_description(a.attrelid,a.attnum) as 字段描述
  13. from pg_attribute a
  14. left join pg_class c on a.attrelid = c.oid
  15. left join pg_type t on a.atttypid = t.oid
  16. left outer join pg_namespace pn on c.relnamespace = pn.oid
  17. left join ( select pd.*
  18. from pg_description pd
  19. where 1=1
  20. and pd.objsubid = 0 ) de on c.oid = de.objoid
  21. where a.attnum >= 0
  22. and relchecks=0
  23. and relkind in ('r','v','m','f','p')
  24. and pn.nspname not in ('pg_catalog','information_schema')
  25. and pn.nspname not like 'pg_toast%'
  26. order by c.relname , a.attnum asc;

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/464406
推荐阅读
相关标签
  

闽ICP备14008679号