gpt4 book ai didi

mysql - MySQL添加外键报错1215

转载 作者:行者123 更新时间:2023-11-29 06:14:28 27 4
gpt4 key购买 nike

我在向系统添加 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;
我相信它也会为它后面的行创建相同的错误。

最佳答案

您不能为不可为 null 的字段提供 ON DELETE SET NULL

关于mysql - MySQL添加外键报错1215,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36627700/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com