Can a Foreign Key be part of a Composite Primary Key for another table?

断了今生、忘了曾经 提交于 2020-02-03 12:24:13

问题


I have two(of many) tables in a music database:

Concerts: ArtistID,ConcertID,ConcetName,VenueID ConcertDetails: ConcertDate, ConcertID, Cost

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?


回答1:


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)
);


来源:https://stackoverflow.com/questions/43576974/can-a-foreign-key-be-part-of-a-composite-primary-key-for-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!