我读到InnoDB自动为外键创建索引。
Does MySQL Workbench automatically create indexes for foreign keys?Does MySQL index foreign key columns automatically?https://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
但是我的某些外键在表中没有索引。检查pharmaceutical_id
外键字段。它没有索引。
| pharmaceuticals_pharmaceuticalcode | CREATE TABLE `pharmaceuticals_pharmaceuticalcode` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code_id` int(11) NOT NULL,
`pharmaceutical_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `pharmaceuticals_pharmaceuticalco_pharmaceutical_id_5ae1e77e_uniq` (`pharmaceutical_id`,`code_id`),
KEY `pharmaceuticals_phar_code_id_a7de9505_fk_human_api` (`code_id`),
CONSTRAINT `pharmaceuticals_phar_code_id_a7de9505_fk_human_api` FOREIGN KEY (`code_id`) REFERENCES `human_api_code` (`id`),
CONSTRAINT `pharmaceuticals_phar_pharmaceutical_id_04c18462_fk_pharmaceu` FOREIGN KEY (`pharmaceutical_id`) REFERENCES `pharmaceuticals_pharmaceutical` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=202770 DEFAULT CHARSET=utf8 COLLATE=utf8_bin |
我在pharmaceutical_id
和code_id
上添加了唯一键约束,这可能导致未为pharmaceutical_id
创建单独的索引,因为MySQL以B-Tree
的方式管理这些索引,并且可以使用唯一键键的索引为此。
检查https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html上的限制和条件的第六点
InnoDB允许外键引用任何索引列或列组。但是,在引用表中,必须有一个索引,其中引用列是相同顺序的第一列。还考虑了InnoDB添加到索引的隐藏列(请参见第14.6.2.1节“聚集索引和二级索引”。)>
但是如果以上观点是正确的,那么为什么在下表结构中有
member_id
的索引?
| patients_membercard | CREATE TABLE `patients_membercard` ( `id` int(11) NOT NULL AUTO_INCREMENT, `member_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `patients_membercard_member_id_661ac31abca894ae_uniq` (`member_id`,`name`), KEY `patients_membercard_b5c3e75b` (`member_id`), CONSTRAINT `patients_member_member_id_459e0d6970a32170_fk_patients_member_id` FOREIGN KEY (`member_id`) REFERENCES `patients_member` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1655520 DEFAULT CHARSET=utf8 COLLATE=utf8_bin |
PS:上表,模式是由
Django
创建的,尚未在DB上执行任何手动操作。
我读到InnoDB自动为外键创建索引。 MySQL Workbench是否会自动为外键创建索引? MySQL是否自动索引外键列? https:// dev ....
您的外键确实具有索引。