【问题标题】:PostgreSQL foreign keyPostgreSQL 外键
【发布时间】:2014-01-09 18:34:56
【问题描述】:

如何检测表的列是否由外键设置,并在 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)
);

【问题讨论】:

    标签: sql database postgresql foreign-keys relational-database


    【解决方案1】:

    您可以通过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”表的外键引用。

    【讨论】:

    • 能否请您举例说明一些变量的外观。例如,我们有一个名为 T1 的表和一个名为 T2 的表。 T1 外部 t2.ID 引用来自(t2.id)
    • 当然。您可以编辑您的问题以添加您的架构吗?您的 create table 语句会很有帮助(您可以更改名称,只需保持结构相同)。
    • 我为您添加了一个额外的示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2021-12-22
    • 2015-04-17
    • 1970-01-01
    • 2014-10-15
    • 2012-03-05
    • 2018-02-21
    相关资源
    最近更新 更多