postgresql 數據庫查找表的主鍵

with tmp_tab as (
	   select n.nspname as schemaname,
			  c.oid as reloid,
			  c.relname ,
			  case c.relkind when 'r' then 'table' 
							 when 'm' then 'materialized view' 
							 when 's' then 'special' 
							 when 'f' then 'foreign table' 
							 when 'p' then 'table' 
			   end as relType,
			  pg_catalog.pg_get_userbyid(c.relowner) as ownername
		from pg_catalog.pg_class c
		     left join pg_catalog.pg_namespace n on n.oid = c.relnamespace
		where 1=1
		  --r = 普通表, i = 索引, S = 序列, t = TOAST表, v = 視圖, m = 物化視圖, c = 組合類型, f = 外部表, p = 分區表, I = 分區索引
		  and  c.relkind IN ('r','p','m','f','')
		  and n.nspname <> 'pg_catalog'
		  and n.nspname <> 'information_schema'
		  and n.nspname !~ '^pg_toast'
		  and pg_catalog.pg_table_is_visible(c.oid)
		order by 1,2
)
select current_database() as databasename,
       tab.schemaname,
       tab.reloid,tab.relname,tab.reltype,tab.ownername,
       pco.conname as pk_name,
       pa.attname as col_name,
       pt.typname as col_type
  from tmp_tab tab
       left outer join pg_constraint pco on pco.conrelid=tab.reloid
                                         and pco.contype = 'p'
       left outer join pg_attribute pa on pa.attrelid=tab.reloid
                                       and pa.attnum= pco.conkey [ 1 ]
       left outer join pg_type pt on pt.oid=pa.atttypid
order by 1,2,4,7           


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章