gpt4 book ai didi

MYSQL 自动创建索引时

转载 作者:太空宇宙 更新时间:2023-11-03 11:30:44 25 4
gpt4 key购买 nike

我有以下主表:

CREATE TABLE IF NOT EXISTS `table_1` (
`id` BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

以及下表:

CREATE TABLE IF NOT EXISTS `table_2` (
`id_1` BIGINT UNSIGNED NOT NULL,
`id_2` BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (`id_1`,`id_2`),
FOREIGN KEY (`id_1`) REFERENCES table_1(`id`) ON DELETE CASCADE,
FOREIGN KEY (`id_2`) REFERENCES table_2(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

由于某些原因,在创建上述表时,我得到了 MYSQL 自动创建的以下索引:

    Keyname Type    Unique  Packed  Column  Cardinality Collation Null  
id_2 BTREE No No id_2 94695 A No

所以 MYSQL 在 table_2 中名为 id_2 的第二列上创建索引。奇怪的是,它不是在两个外键上创建的,如果我只创建 1 个外键,MYSQL 不会创建这样的索引。

我试图删除索引并收到以下错误:

 Cannot drop index 'id_2': needed in a foreign key constraint

那么为什么 MYSQL 需要创建这样的索引,为什么要在两个键上创建它??

最佳答案

与其他数据库不同,MySQL 为外键约束创建索引。如 documentation 中所述:

index_name represents a foreign key ID. The index_name value is ignored if there is already an explicitly defined index on the child table that can support the foreign key. Otherwise, MySQL implicitly creates a foreign key index that is named according to the following rules: . . .

在您的例子中,其中一个外键声明由主键索引处理,因为 id_1 是它们中的第一个键。

关于MYSQL 自动创建索引时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50086905/

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