请考虑以下我在MySQL 8.0.22(在InnoDB数据库中)中运行的SQL代码:
CREATE TABLE `person` (
`person_id` smallint unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
PRIMARY KEY (`person_id`)
);
CREATE TABLE `pet` (
`pet_id` smallint unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
PRIMARY KEY (`pet_id`)
);
ALTER TABLE `pet`
ADD COLUMN `owner_id` smallint unsigned;
ALTER TABLE `pet`
ADD CONSTRAINT `fk_pet_person`
FOREIGN KEY `idx_fk_pet_person` (`owner_id`)
REFERENCES `person` (`person_id`);
SHOW CREATE TABLE pet;
输出SHOW CREATE TABLE pet
为:
CREATE TABLE `pet` (
`pet_id` smallint unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`owner_id` smallint unsigned DEFAULT NULL,
PRIMARY KEY (`pet_id`),
KEY `fk_pet_person` (`owner_id`),
CONSTRAINT `fk_pet_person` FOREIGN KEY (`owner_id`) REFERENCES `person` (`person_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
在上面的输出中,fk_pet_person
当我idx_fk_pet_person
在ALTER TABLE
命令中指定其名称时,为什么要命名KEY ?我怎样才能这样命名呢?
您会混淆使它起作用的FOREIGN KEY和INDEX。请注意-在代码中显示的约束定义中没有表达式名称(看起来像索引定义,但看起来没有)。
如果没有合适的索引使约束起作用,则将自动创建此索引,并将约束名称用作索引名称。如果存在合适的索引,则不会发生自动创建。
如果希望索引具有定义的名称,则必须在创建ALTER TABLE
约束之前在单独的(子)语句中创建此索引:
ALTER TABLE `pet`
ADD KEY `idx_fk_pet_person` (`owner_id`),
ADD CONSTRAINT `fk_pet_person`
FOREIGN KEY (`owner_id`)
REFERENCES `person` (`person_id`);
要么
ALTER TABLE `pet`
ADD KEY `idx_fk_pet_person` (`owner_id`);
ALTER TABLE `pet`
ADD CONSTRAINT `fk_pet_person`
FOREIGN KEY (`owner_id`)
REFERENCES `person` (`person_id`);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句