我知道序列名称,但不知道它的表名称和列名称。 因此,请帮助我找到它。
答案 0 :(得分: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');
答案 1 :(得分: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%'
这对于列不拥有的序列也适用。