mysql多个外键删除设置,Mysql创建表与多个外键删除设置null

I am trying to create a database with multiple foreign keys with delete/ update constraints, but I got a error code 1005 with following sql scripts:

CREATE TABLE Worker (

WorkerID smallint auto_increment,

WorkerType varchar(45) NOT NULL,

WorkerName varchar(45) NOT NULL,

Position varchar(45) NOT NULL,

TaxFileNumber int NOT NULL,

Address varchar(100) ,

Phone varchar(20) ,

SupervisorID smallint ,

PRIMARY KEY (WorkerID),

FOREIGN KEY (SupervisorID) REFERENCES Worker(WorkerID)

ON DELETE SET NULL

ON UPDATE CASCADE

)Engine=InnoDB;

CREATE TABLE Grape (

GrapeID smallint NOT NULL,

GrapeType varchar(45) NOT NULL,

JuiceConversionRatio int,

StorageContainer ENUM('Stainless Steel Tank','Oak Barrel'),

AgingRequirement int,

PRIMARY KEY (GrapeID)

)Engine=InnoDB;

CREATE TABLE Vineyard (

VineyardID smallint auto_increment,

VineyardName VARCHAR(45) NOT NULL,

FarmerID smallint NOT NULL,

GrapeID smallint NOT NULL,

ComeFrom varchar(45) NOT NULL,

HarvestedAmount int,

RipenessPercent int,

PRIMARY KEY (VineyardID),

FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)

ON DELETE SET NULL

ON UPDATE CASCADE,

FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)

ON DELETE SET NULL

ON UPDATE CASCADE

)Engine=InnoDB;

The error code says that fail to create the Vineyard table, I just want to know the proper format for creating multiple foreign keys with delete/update control.

解决方案

Your foreign key rule is ON DELETE SET NULL but your column definition is NOT NULL.

Either change your column definition and remove the NOT NULL part or overthink your foreign key rule. That works:

CREATE TABLE Vineyard (

VineyardID smallint auto_increment,

VineyardName VARCHAR(45) NOT NULL,

FarmerID smallint,

GrapeID smallint,

ComeFrom varchar(45) NOT NULL,

HarvestedAmount int,

RipenessPercent int,

PRIMARY KEY (VineyardID),

FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)

ON DELETE SET NULL

ON UPDATE CASCADE,

FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)

ON DELETE SET NULL

ON UPDATE CASCADE

)Engine=InnoDB;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值