Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
838 views
in Technique[技术] by (71.8m points)

mysql - ERROR 1215: Cannot add foreign key constraint when using ON DELETE SET NULL

I'm trying to create the following tables in MySQL. The first one:

CREATE TABLE IF NOT EXISTS address(
  address_id INT NOT NULL AUTO_INCREMENT,
  address_region VARCHAR(10) NOT NULL,
  address_country VARCHAR(20) NOT NULL,
  address_city VARCHAR(30) NOT NULL,
  PRIMARY KEY(address_id))ENGINE = InnoDB;

I created it successfully,but when I try to create another table as following

CREATE TABLE IF NOT EXISTS spot(
  spot_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  spot_address INT(11) NOT NULL,
  spot_name VARCHAR(50) NOT NULL,
  spot_desc VARCHAR(500) DEFAULT ' ',
  spot_speadd VARCHAR(100) NOT NULL,
  spot_viewtime INT DEFAULT 0,
  FOREIGN KEY(spot_address)
  REFERENCES address(address_id)
  ON DELETE SET NULL
  ON UPDATE SET NULL);

I get an error:

ERROR 1215 (HY000): Cannot add foreign key constraint

Why is this create table statement failing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have NOT NULL constraint on spot_address in the spot table and then try to set it to NULL on delete or update in the parent table address.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...