怎么在postgresql中获取所有的表名和字段名?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
获取表名及注释:
select relname as tabname,cast(obj_description(relfilenode,'pg_class') as varchar) as comment from pg_class c where relkind = 'r' and relname not like 'pg_%' and relname not like 'sql_%' order by relname
过滤掉分表:
加条件 and relchecks=0
即可
获取字段名、类型、注释、是否为空:
SELECT col_description(a.attrelid,a.attnum) as comment,format_type(a.atttypid,a.atttypmod) as type,a.attname as name, a.attnotnull as notnull FROM pg_class as c,pg_attribute as a where c.relname = '表名' and a.attrelid = c.oid and a.attnum>0
补充:PostgreSQL查询表主键及注释内容
网上关于pgSql获取表主键的内容都是千篇一律,并且对于存在多主键的场景不支持。
附上测试后可获取多个主键字段值的SQL
SELECT string_agg(DISTINCT t3.attname,',') AS primaryKeyColumn ,t4.tablename AS tableName , string_agg(cast(obj_description(relfilenode,'pg_class') as varchar),'') as comment FROM pg_constraint t1 INNER JOIN pg_class t2 ON t1.conrelid = t2.oid INNER JOIN pg_attribute t3 ON t3.attrelid = t2.oid AND array_position(t1.conkey,t3.attnum) is not null INNER JOIN pg_tables t4 on t4.tablename = t2.relname INNER JOIN pg_index t5 ON t5.indrelid = t2.oid AND t3.attnum = ANY (t5.indkey) LEFT JOIN pg_description t6 on t6.objoid=t3.attrelid and t6.objsubid=t3.attnum WHERE t1.contype = 'p' AND length(t3.attname) > 0 AND t2.oid = '表名' :: regclass group by t4.tablename
目前只找到了获取指定表的主键信息,对于批量获取没有找到。
看完上述内容,你们掌握怎么在postgresql中获取所有的表名和字段名的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。