简体   繁体   English

如何制作引用由多个外键组成的另一个主键的外键?

[英]How do I make a foreign primary key that references to another primary key that is made of multiple foreign keys?

I've currently got something like this on one table: 我目前在一张桌子上有这样的东西:

create table NetWorth (
    id int,
    id_movie int foreign key references Movie(id),
    primary key (id, id_movie)
    )    

And want to make a reference to its primary key, which is made of up 2 attributes, its own ID and the ID of the Movie table. 并且要引用其主键,该主键由2个属性组成,即其自己的ID和Movie表的ID。 Currently, I was thinking something like this: 目前,我在想这样的事情:

create table Merchandising (
    id_networth int foreign key references NetWorth(id) primary key,
    value float
    )

But obviously it's wrong, because it's missing the second key reference, and I don't know how to implement it in the second table. 但是显然这是错误的,因为它缺少第二个关键参考,而且我不知道如何在第二个表中实现它。 So could you guys help me out? 你们可以帮我吗?

If the primary key you want to reference is made up from multiple columns, all foreign keys referencing it must also have and use all those columns. 如果要引用的主键由多列组成,则引用该主键的所有外键也必须具有并使用所有这些列。 You can't just reference half a primary key - it's all or nothing. 您不能只引用一半的主键-全部或全部。

Since the FK references two columns in your case, you cannot apply the FOREIGN KEY constraint syntax to a single column - use this instead: 由于FK在您的情况下引用了两列 ,因此您无法将FOREIGN KEY约束语法应用于单个列-而是使用此语法:

create table Merchandising 
(
    id_networth int 
       constraint PK_Merchandising primary key,
    id_movie int,
    value float,

    constraint FK_Merchandising_Networth
       foreign key(id, id_movie) references NetWorth(id, id_movie) 
)

And I would also recommend to always specify an explicit name for your constraints - both your primary key constraints, as well as your foreign key constraints (and also all others you might have). 而且我还建议始终为约束指定一个明确的名称 -主键约束和外键约束(以及所有其他可能的约束)。

As you mention in the comments, NetWorth.Id is unique, and so is probably the only column you should define as the primary key, not id, id_movie . 正如您在评论中提到的那样, NetWorth.Id是唯一的,因此可能是您应该定义为主键而不是id, id_movie的唯一列id, id_movie

Once you make that change, you will no longer have an issue creating your foreign key reference from the Merchandising table. 进行更改后,从Merchandising表创建外键引用将不再有问题。

EDIT : 编辑

Your table creation statements could look like this (though I agree with marc_s that you should explicitly name the constraints): 您的表创建语句可能看起来像这样(尽管我同意marc_s,您应该明确命名约束):

create table NetWorth (
  id int primary key,
  id_movie int foreign key references Movie(id)
)

create table Merchandising (
  id_networth int foreign key references NetWorth(id) primary key,
  value float
)

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

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