Unfortunately I don't have enough rep to comment on ypercubeᵀᴹ's answer, so I'll post an alternate answer instead - I agree with that answer in general but think the primary key and unique contraints on AlbumTrack
are incorrect given that albums and tracks are both weak entities. For example, the following valid data would, with the prescribed constraints, be disallowed:
artistID | albumID | trackID | trackNo
----------+---------+---------+---------
1 | 1 | 1 | 1
2 | 1 | 1 | 1
Instead I would set PRIMARY KEY (artistID, albumID, trackID)
and drop the unique constraint, resulting in:
CREATE TABLE Artist
( artistID INT NOT NULL
, name VARCHAR(100) NOT NULL
, PRIMARY KEY (artistID)
) ;
CREATE TABLE Album
( artistID INT NOT NULL
, albumID INT NOT NULL
, title VARCHAR(100) NOT NULL
, PRIMARY KEY (artistID, albumID)
, FOREIGN KEY (artistID)
REFERENCES Artist (artistID)
) ;
CREATE TABLE Track
( artistID INT NOT NULL
, trackID INT NOT NULL
, title VARCHAR(100) NOT NULL
, PRIMARY KEY (artistID, trackID)
, FOREIGN KEY (artistID)
REFERENCES Artist (artistID)
) ;
CREATE TABLE AlbumTrack
( artistID INT NOT NULL
, albumID INT NOT NULL
, trackID INT NOT NULL
, trackNo INT NOT NULL
, PRIMARY KEY (artistID, albumID, trackID)
, FOREIGN KEY (artistID, albumID)
REFERENCES Album (artistID, albumID)
, FOREIGN KEY (artistID, trackID)
REFERENCES Track (artistID, trackID)
) ;
Tracks are still constrained to occur at most once per album.
Also, the question doesn't actually specify that tracks are weak entities (only that albums are) - if tracks can in fact exist independent of artists, the Track
and AlbumTrack
tables are defined slightly differently:
CREATE TABLE Track
( trackID INT NOT NULL
, artistID INT
, title VARCHAR(100) NOT NULL
, PRIMARY KEY trackID
, FOREIGN KEY (artistID)
REFERENCES Artist (artistID)
) ;
CREATE TABLE AlbumTrack
( artistID INT NOT NULL
, albumID INT NOT NULL
, trackID INT NOT NULL
, trackNo INT NOT NULL
, PRIMARY KEY (artistID, albumID, trackID)
, FOREIGN KEY (artistID, albumID)
REFERENCES Album (artistID, albumID)
, FOREIGN KEY (trackID)
REFERENCES Track (trackID)
) ;