Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 510
DJPharaohCHS Avatar asked Apr 23 '17 22:04

DJPharaohCHS


People also ask

Can a foreign key be a primary key in another table?

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table. The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.

Can a primary key be a foreign key to another primary key?

A foreign key is a set of one or more columns in any table (not necessarily a candidate key, let alone the primary key, of that table) which may hold the value(s) found in the primary key column(s) of some other table. So we must have a primary key to match the foreign key.

Can a foreign key be a partial key?

A foreign key is a relationship between two entities.


1 Answers

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)
);
like image 71
Bill Karwin Avatar answered Oct 12 '22 06:10

Bill Karwin