gpt4 book ai didi

mysql - 为什么 MySQL 没有正确命名我的外键?

转载 作者:行者123 更新时间:2023-12-02 19:01:43 24 4
gpt4 key购买 nike

请考虑我在 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

在上面的输出中,当我在 ALTER TABLE 命令中将其名称指定为 idx_fk_pet_person 时,为什么 KEY 的名称为 fk_pet_person?我怎样才能让它如此命名?

最佳答案

您混淆了外键和使其工作的索引。请注意 - 代码中显示的约束定义中没有表达式名称(看起来像索引定义,但实际上不是)。

当没有合适的索引让约束起作用时,会自动创建该索引,并使用约束名称作为索引名称。如果存在合适的索引,则不会发生自动创建。

如果您希望索引具有已定义的名称,则必须在创建约束之前在单独的 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`);

DEMO

关于mysql - 为什么 MySQL 没有正确命名我的外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65481202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com