2014-01-09 49 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