MySQL - 删除时的外键在非空字段中设置为null

时间:2013-12-16 04:22:57

标签: mysql sql foreign-key-relationship create-table notnull

这可能是一个微不足道的问题,但在涉及外键约束时我仍然有点笨拙,所以我想确定。

假设我的表格countries包含字段country_id(PK)和name,表格cities包含字段city_id(PK ),namecountry_id(FK)。

外键cities.country_id具有约束ON DELETE SET NULL。据我了解,这意味着如果删除countries中的记录,cities中引用该已删除记录的country_id的任何记录都会将其country_id字段设置为NULL

但是,如果cities.country_id具有属性NOT NULL,该怎么办?这会阻止外键约束正常工作吗?它确实有意义,但我只是想检查一下。

1 个答案:

答案 0 :(得分:1)

如果您将ON DELETE SET NULL设置为外键,则不允许您将字段设置为NOT NULL

因此,您无法在 CountryId

上创建或更改包含NOT NULLON DELETE SET NULL列的表格

当我在下面的陈述中运行时:

CREATE TABLE `country` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;

CREATE TABLE `city` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `countryId` int(10) unsigned DEFAULT NOT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_country` (`countryId`),
  CONSTRAINT `FK_country` FOREIGN KEY (`countryId`) REFERENCES `country` (`id`) ON DELETE SET NULL ON UPDATE SET NULL
);

我在MySQL 5.5中收到的错误是:

Schema Creation Failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NOT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_country` (`countryId`),
  CONSTRAINT `' at line 4: