[英]PostgreSQL foreign key
如何檢測表的列是否由外鍵設置,並在Postgres中獲取引用表的名稱?
我需要這個信息用於java GUI。 所以SQL解決方案是可以解決的最佳方式,我真的無法管理它。
尊重斯特凡
例:
create table SUREALTABLE(
VNR varchar(5),
tnumberone integer,
tnumbertwo integer,
foreign key (tnumberone ,tnumbertwo) references TESTTABLE(numberone,numbertwo),
primary key (VNR)
);
create table TESTTABLE(
numberone integer,
numbertwo integer,
primary key (numberone, numbertwo)
);
您可以使用pg_catalog.pg_constraint
和pg_catalog.pg_attribute
( 此處有更多信息)來確定。
select a.confrelid::regclass,
b.attname
from pg_constraint a
join pg_attribute b
on a.conrelid = b.attrelid
and b.attnum = any (a.conkey)
where a.conrelid = '<tablename>'::regclass
and a.contype = 'f'
;
您可以使用b.attname對其進行過濾。
更具體的例子:
select a.confrelid::regclass
from pg_constraint a
join pg_attribute b
on a.conrelid = b.attrelid
and b.attnum = any (a.conkey)
where a.conrelid = 'SUREALTABLE'::regclass
and a.contype = 'f'
and b.attname = 'tnumberone'
;
這將返回“testtable”,表示表“surealtable”的列“tnumberone”具有對表“testtable”的外鍵引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.