MYSQL 自动创建索引
MYSQL creates index automatically when
我有以下主要内容table:
CREATE TABLE IF NOT EXISTS `table_1` (
`id` BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
以及以下 table:
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;
出于某种原因,在创建上述 table 时,我得到了 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
是它们中的第一个键。
我有以下主要内容table:
CREATE TABLE IF NOT EXISTS `table_1` (
`id` BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
以及以下 table:
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;
出于某种原因,在创建上述 table 时,我得到了 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
是它们中的第一个键。