0

我知道序列名称,但我不知道它的表名和列名。所以请帮助我如何找到它。

4

2 回答 2

1

使用@a_horse_with_no_name 的回答进行轻微即兴创作。下面的查询还将给出模式名称和序列名称。因此,这为您提供了具有模式、表、列和序列名称的数据作为单个结果

select ts.nspname as object_schema,
        tbl.relname as table_name, 
       col.attname as column_name,
       s.relname   as sequence_name
from pg_class s
  join pg_namespace sn on sn.oid = s.relnamespace 
  join pg_depend d on d.refobjid = s.oid and d.refclassid='pg_class'::regclass 
  join pg_attrdef ad on ad.oid = d.objid and d.classid = 'pg_attrdef'::regclass
  join pg_attribute col on col.attrelid = ad.adrelid and col.attnum = ad.adnum
  join pg_class tbl on tbl.oid = ad.adrelid 
  join pg_namespace ts on ts.oid = tbl.relnamespace 
where s.relkind = 'S'
--  and s.relname = 'your_sequence_name_here'
  and d.deptype in ('a', 'n');
于 2021-03-24T12:51:38.170 回答
0

假设它是一个列所拥有的序列,例如因为该列被定义为serial或者identity然后您可以通过查看 pg_depend 来获取该信息并将其加入pg_class(和其他)

select tbl.relname as table_name, 
       col.attname as column_name
from pg_class s
  join pg_namespace sn on sn.oid = s.relnamespace 
  join pg_depend d on d.refobjid = s.oid and d.refclassid='pg_class'::regclass 
  join pg_attrdef ad on ad.oid = d.objid and d.classid = 'pg_attrdef'::regclass
  join pg_attribute col on col.attrelid = ad.adrelid and col.attnum = ad.adnum
  join pg_class tbl on tbl.oid = ad.adrelid 
  join pg_namespace ts on ts.oid = tbl.relnamespace 
where s.relkind = 'S'
  and s.relname = 'your_sequence_name_her'
  and d.deptype in ('a', 'n');

另一种选择是查看列的默认值并检查它是否包含序列名称:

select tbl.relname as table_name, 
       col.attname as column_name
from pg_attrdef ad
  join pg_attribute col on col.attrelid = ad.adrelid and col.attnum = ad.adnum
  join pg_class tbl on tbl.oid = ad.adrelid
where adsrc like '%your_sequence_name_her%'

这也适用于不属于列的序列。

于 2019-03-29T09:53:56.373 回答