简体   繁体   English

postgresql中的双外键

[英]Double Foreign key in postgresql

I am trying to use a double primary key as a foreign key. 我试图使用双主键作为外键。

Create table AAA (
   AAA_id int primary key
);

create table BBB (
   AAA_id int,
   BBB_name character varying(20),
   primary key (AAA_id, BBB_name)
);

create table CCC (
    AAA_id,
    BBB_name,
    DDD_id,

    ... ???
);

table AAA is an object 表AAA是一个对象

table BBB is many to one with AAA, and holds aliases of AAA 表BBB与AAA有多对一,并且拥有AAA的别名

I am trying to create a pivot table, CCC which holds a many to one between DDD and BBB. 我正在尝试创建一个数据透视表,CCC在DDD和BBB之间保持多对一。

I guess I want something like 我想我想要的东西

create table CCC (
    AAA_id,
    BBB_name,
    DDD_id,
    foreign key (AAA_id, BBB_name) references BBB(AAA_id, BBB_name) on update cascade
);

where both AAA_id and BBB_name are foreign keys, but they are also always referring to the same row in BBB. 其中AAA_id和BBB_name都是外键,但它们也始终引用BBB中的同一行。

but of course that's not valid. 但当然这是无效的。 what is the best way to produce this type of behavior in postgreSQL? 在postgreSQL中产生这种行为的最佳方法是什么?

Create temp table AAA (
   AAA_id int primary key
);

create temp table BBB (
   AAA_id int not null references AAA (AAA_id),
   BBB_name character varying(20) not null,
   primary key (AAA_id, BBB_name)
);

create temp table CCC (
    AAA_id int not null,
    BBB_name character varying(20) not null,
    DDD_id integer not null,
    -- Guessing at the primary key.
    primary key (AAA_id, BBB_name, DDD_id),
    foreign key (AAA_id, BBB_name) references BBB (AAA_id, BBB_name) 
        on update cascade
);

Since {AAA_id, BBB_name} uniquely identify a row in BBB, the foreign key {AAA_id, BBB_name} in CCC will also reference one unique row in BBB. 由于{AAA_id,BBB_name}唯一地标识BBB中的行,因此CCC中的外键{AAA_id,BBB_name}也将引用BBB中的一个唯一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM