最近在整理postgresql数据库的表、列的备注信息时,用到了如下的sql
表的备注
with tmp_tab as (
select pc.oid,pc.*
from pg_class pc
where 1=1
and pc.relkind in ('r')
and pc.relnamespace = 2200 -- select pn.oid, pn.* from pg_namespace pn where 1=1
and pc.oid not in (
select inhrelid
from pg_inherits
)
and pc.relname not like '%peiyb%'
order by pc.relname
),tmp_desc as (
select pd.*
from pg_description pd
where 1=1
and pd.objsubid = 0
--and pd.objoid=168605
)
select tab.relname,
de.description
from tmp_tab tab
left outer join tmp_desc de
on tab.oid = de.objoid
order by tab.relname
;
列的备注
with tmp_tab as (
select pc.oid,pc.*
from pg_class pc
where 1=1
and pc.relkind in ('r')
and pc.relnamespace = 2200 -- select pn.oid, pn.* from pg_namespace pn where 1=1
and pc.oid not in (
select inhrelid
from pg_inherits
)
and pc.relname not like '%peiyb%'
order by pc.relname
),tmp_col as (
select pa.*
from pg_attribute pa
where 1=1
--and pa.attrelid = 168605
and pa.attname not in (
'tableoid',
'cmax',
'xmax',
'cmin',
'xmin',
'ctid'
)
),tmp_desc as (
select pd.*
from pg_description pd
where 1=1
and pd.objsubid <> 0
--and pd.objoid=168605
)
select tab.relname,
tc.attname,
de.description
from tmp_tab tab
left outer join tmp_col tc
on tab.oid = tc.attrelid
left outer join tmp_desc de
on tc.attrelid = de.objoid and tc.attnum = de.objsubid
order by tab.relname, tc.attnum
;
参考:
http://postgres.cn/docs/9.6/catalog-pg-class.html
http://postgres.cn/docs/9.6/catalog-pg-attribute.html
http://postgres.cn/docs/9.6/catalog-pg-description.html