当我尝试创建一个名为Sales的表时,MySQL会出现以下错误。我不知道问题是什么,我瞥了一眼http://dev.mysql.com/doc/refman/4.1/en/innodb-foreign-key-constraints.html,看看我犯了什么错,但我说不出来。 我在MySQL 5.6.11中遇到此错误,但在5.1.67
中没有Error
SQL query:
CREATE TABLE IF NOT EXISTS Sales(
name VARCHAR( 30 ) NOT NULL ,
address VARCHAR( 70 ) NOT NULL ,
serialsold VARCHAR( 20 ) UNIQUE NOT NULL ,
background_check VARCHAR( 9 ) NOT NULL ,
soldfor FLOAT NOT NULL ,
datesold TIMESTAMP DEFAULTNOW( ) ,
FOREIGN KEY ( serialsold ) REFERENCES Guns( serialnumber ) ON DELETE SET NULL ON UPDATE CASCADE ,
PRIMARY KEY ( background_check )
);
MySQL said: Documentation
#1215 - Cannot add foreign key constraint
我的枪支和购买表:
CREATE TABLE IF NOT EXISTS Purchases
(
name VARCHAR(30) NOT NULL,
address VARCHAR(70) NOT NULL,
serialbought VARCHAR(20) UNIQUE NOT NULL,
boughtfor FLOAT,
datebought TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (serialbought)
);
CREATE TABLE IF NOT EXISTS Guns
(
sequence INTEGER(4) NOT NULL AUTO_INCREMENT,
manufacturer VARCHAR(30) NOT NULL,
model VARCHAR(20) NOT NULL,
caliber VARCHAR(10) NOT NULL,
serialnumber VARCHAR(20) UNIQUE NOT NULL,
type VARCHAR(10) NOT NULl,
sellsfor FLOAT DEFAULT NULL,
FOREIGN KEY (serialnumber) REFERENCES Purchases(serialbought)
ON DELETE RESTRICT ON UPDATE RESTRICT,
PRIMARY KEY (sequence)
);
答案 0 :(得分:9)
您将字段serialsold
定义为不可为空 -
serialsold VARCHAR( 20 ) UNIQUE NOT NULL
但是你试图用SET NULL子句添加动作 -
ON DELETE SET NULL
更改其中一个选项并尝试创建表。