SQL 引用外键

SQL referencing foreign key

我无法使 Album table 上的 GenreID 外键起作用。有人知道为什么吗?

CREATE TABLE ArtistBand 
(
     ArtistID INT AUTO_INCREMENT PRIMARY KEY,
     BandName VARCHAR(255) NOT NULL,
     NameOfMembers VARCHAR(255),
     NumberOfMembers INT
);

CREATE TABLE Genre
(
     GenreID INT AUTO_INCREMENT PRIMARY KEY,
     GenreType VARCHAR(255) NOT NULL,
     AlbumID INT,
     FOREIGN KEY(AlbumID) REFERENCES Album(AlbumID)
);

CREATE TABLE Album 
(
    AlbumID INT AUTO_INCREMENT PRIMARY KEY,
    Name VARCHAR (255) NOT NULL,
    ReleaseDate DATE NOT NULL,
    Producers VARCHAR (255),
    ArtistID INT,
    GenreID INT,

    FOREIGN KEY(ArtistID) REFERENCES ArtistBand(ArtistID),
    FOREIGN KEY (GenreID) REFERENCES Genre (GenreID)
);

去掉GenreAlbum之间的循环外键引用。从逻辑上讲,从 GenreAlbum 的引用无论如何都没有任何意义 :).

CREATE TABLE ArtistBand (
ArtistID INT AUTO_INCREMENT PRIMARY KEY,
BandName VARCHAR(255) NOT NULL,
NameOfMembers VARCHAR(255),
NumberOfMembers INT
);

CREATE TABLE Genre(
GenreID INT AUTO_INCREMENT PRIMARY KEY,
GenreType VARCHAR(255) NOT NULL
);

CREATE TABLE Album (
AlbumID INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR (255) NOT NULL,
ReleaseDate DATE NOT NULL,
Producers VARCHAR (255),
ArtistID INT,
GenreID INT,
FOREIGN KEY(ArtistID) REFERENCES ArtistBand(ArtistID),
FOREIGN KEY (GenreID) REFERENCES Genre (GenreID)
);

如果使用sql服务器:auto_increment修改为身份

CREATE TABLE ArtistBand (
ArtistID INT identity(1,1) PRIMARY KEY,
BandName VARCHAR(255) NOT NULL,
NameOfMembers VARCHAR(255),
NumberOfMembers INT
);

CREATE TABLE Genre(
GenreID INT identity(1,1) PRIMARY KEY,
GenreType VARCHAR(255) NOT NULL
);

CREATE TABLE Album (
AlbumID INT identity(1,1) PRIMARY KEY,
Name VARCHAR (255) NOT NULL,
ReleaseDate DATE NOT NULL,
Producers VARCHAR (255),
ArtistID INT,
GenreID INT,
FOREIGN KEY(ArtistID) REFERENCES ArtistBand(ArtistID),
FOREIGN KEY (GenreID) REFERENCES Genre (GenreID)
);