2014-01-09 45 views
0

如何通过外键检测表的列是否被设置,并在Postgres中获取被引用表的名称?PostgreSQL外键

我需要此信息的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) 
); 

回答

2

您可以确定与pg_catalog.pg_constraintpg_catalog.pg_attribute(更多信息here)。

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的”。

+0

可以请给出例子,看看如何用一些变量..例如,我们有一个名为T1和表T2的表。来自(t2.id)的T1外来t2.ID引用 –

+0

当然。你能编辑你的问题来添加你的模式吗?你创建的表格语句会很有帮助(你可以改变名称,只保留结构相同)。 – yieldsfalsehood

+0

我为你增加了一个例子。 – yieldsfalsehood