外键可以成为另一个表的组合主键的一部分吗? [英] Can a Foreign Key be part of a Composite Primary Key for another table?
问题描述
我在音乐数据库中有两个(很多)表:
I have two(of many) tables in a music database:
音乐会:ArtistID,ConcertID,ConcetName,VenueID ConcertDetails:ConcertDate,ConcertID,费用
Concerts: ArtistID,ConcertID,ConcetName,VenueID ConcertDetails: ConcertDate, ConcertID, Cost
如您所见,ConcertDetails表使用了ConcertID表中的ConcertID.我将ConcertDate& amp; ConcertID为ConcertDetails制作一个复合主键.但是,由于这与Concerts表中的ConcertID有关,因此它也必须是外键.这样可以吗?
The ConcertDetails tables as you see, uses ConcertID which is also in the Concerts table. I combine ConcertDate & ConcertID to make a Composite Primary Key for ConcertDetails. However since this relates to ConcertID from Concerts table it also needs to be a Foreign Key. Is this ok to do?
推荐答案
当然可以.主键的子集通常是外键.例如,任何多对多表都可以执行此操作.就您而言:
Yes, of course. It's common for a subset of a primary key to be a foreign key. Any many-to-many table does this for instance. In your case:
CREATE TABLE ConcertDetails (
ConcertDate DATE NOT NULL,
ConcertID INT NOT NULL,
PRIMARY KEY (ConcertDate, ConcertID),
FOREIGN KEY (ConcertID) REFERENCES Concerts(ConcertID)
);
这篇关于外键可以成为另一个表的组合主键的一部分吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!