错误1215:使用ON DELETE SET NULL时无法添加外键约束

我试图在MySQL中创建下列表格。 第一个:

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;

我创建它成功,但是当我尝试创建另一个表如下

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);

我收到一个错误:

错误1215(HY000):无法添加外键约束

为什么这个创建表语句失败?


您在spot表中的spot_address上有NOT NULL约束,然后尝试在删除或更新父表address将其设置为NULL


你可以试试这个:

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;




CREATE TABLE IF NOT EXISTS `spot`
(
  `spot_id` INT(11) NOT NULL AUTO_INCREMENT,
  `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(11) DEFAULT '0',
  PRIMARY KEY (`spot_id`),
  KEY `spot_address` (`spot_address`),
  CONSTRAINT `spot_ibfk_1` FOREIGN KEY (`spot_address`) REFERENCES `address` (`address_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
链接地址: http://www.djcxy.com/p/86273.html

上一篇: ERROR 1215: Cannot add foreign key constraint when using ON DELETE SET NULL

下一篇: Error Code: 1215. Cannot add foreign key constraint (foreign keys)