添加外键

时间:2016-04-14 15:33:17

标签: mysql

我在向系统添加Foreign Keys时收到错误,错误显示为Cannot add foreign key constraint,而我的代码是:

DROP TABLE IF EXISTS Formed;
DROP TABLE IF EXISTS Album;
DROP TABLE IF EXISTS Band;
DROP TABLE IF EXISTS Customers;
DROP TABLE IF EXISTS Track;

CREATE TABLE Formed(
    FormedID int NOT NULL, 
    YearFormed int, 
    CountryFormed varchar(50), 
    CityFormed varchar(50), 
    BandMembers varchar(400), 
    PRIMARY KEY(FormedID))
    ENGINE=InnoDB;

CREATE TABLE Track (
    TrackID int NOT NULL, 
    AlbumID int NOT NULL,
    Songs varchar (100), 
    TrackNumber varchar (20), 
    Title varchar (30), 
    TrackDuration varchar (4), 
    PRIMARY KEY (TrackID)) 
    ENGINE=InnoDB;

CREATE TABLE Album(
    AlbumID int NOT NULL,
    TrackID int NOT NULL,
    BandID int NOT NULL,
    KEY(TrackID),
    KEY(BandID),
    Price varchar(5), 
    PublicationDate varchar(11), 
    Title varchar(30), 
    Genre varchar (36),
    PRIMARY KEY(AlbumID))
    ENGINE=InnoDB;

CREATE TABLE Band(
    BandID int NOT NULL, 
    AlbumID int NOT NULL, 
    KEY(AlbumID),
    RecordLabel varchar(50), 
    PRIMARY KEY(BandID))
    ENGINE=InnoDB;

CREATE TABLE Customers (
    CustomerID int NOT NULL, 
    CName varchar (20), 
    CPhone int (11), 
    CEmail varchar (50), 
    CPPaid varchar (50), 
    CPDate date, 
    PRIMARY KEY (CustomerID))
    ENGINE=InnoDB;

ALTER TABLE Track 
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE Album
ADD FOREIGN KEY (TrackID) REFERENCES Track(TrackID)ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE Album
ADD FOREIGN KEY (BandID) REFERENCES Band(BandID)ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE Band
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE;

我刚才将Foreign Keys添加到MySQL,我不明白我是如何收到此错误的。当它遇到ALTER TABLE Track ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE;行时我收到错误,我相信它会为它后面的行创建相同的错误。

1 个答案:

答案 0 :(得分:2)

您无法为不可为空的字段提供ON DELETE SET NULL