Bob*_*obe 5 mysql sql foreign-key-relationship create-table notnull
这可能是一个微不足道的问题,但在外键约束方面我仍然有点笨拙,所以我想确定一下。
假设我有一个包含countries字段country_id(PK) 和 ( FK) 的表name,以及一个cities包含字段city_id(PK)name和country_id(FK) 的表。
外键cities.country_id有约束ON DELETE SET NULL。countries据我了解,这意味着如果删除记录,则cities该删除记录的引用中的任何记录country_id都将其country_id字段设置为 NULL。
但是,如果cities.country_id具有属性怎么办NOT NULL?这会阻止外键约束正常工作吗?确实如此,但我只是想检查一下。
如果您设置ON DELETE SET NULL为外键,则它将不允许您将该字段设置为NOT NULL。
因此,您将无法创建或更改列为NOT NULLCountryId的ON 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
);
Run Code Online (Sandbox Code Playgroud)
我得到的错误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:
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15263 次 |
| 最近记录: |