[英]PostgreSQL foreign key
how to detect if a column of a table is set by a foreign key, and get the name of the referenced table, in Postgres? 如何检测表的列是否由外键设置,并在Postgres中获取引用表的名称?
I need this Information for a java GUI. 我需要这个信息用于java GUI。 So SQL solution is the best way it could be solved, i really can't manage it. 所以SQL解决方案是可以解决的最佳方式,我真的无法管理它。
regards stefan 尊重斯特凡
example: 例:
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)
);
You can determine that with pg_catalog.pg_constraint
and pg_catalog.pg_attribute
(more info here ). 您可以使用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'
;
You can filter that down using b.attname. 您可以使用b.attname对其进行过滤。
More concrete example: 更具体的例子:
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'
;
This returns "testtable", indicating that the column "tnumberone" of the table "surealtable" has a foreign key reference to the table "testtable". 这将返回“testtable”,表示表“surealtable”的列“tnumberone”具有对表“testtable”的外键引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.