MySQL是否自动索引外键列?
当前回答
是的,但只在innodb上。Innodb是目前唯一实现了外键的表格式。
其他回答
如果你做ALTER TABLE(而不是CREATE TABLE),你不会自动得到索引,至少根据文档(链接是5.1的,但5.5也是一样的):
[…当您使用ALTER table向表添加外键约束时,请记住首先创建所需的索引。
显然,一个索引是自动创建的,就像罗伯特发布的链接中指定的那样。
InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. (This is in contrast to some older versions, in which indexes had to be created explicitly or the creation of foreign key constraints would fail.) index_name, if given, is used as described previously.
InnoDB和外键约束
对于那些正在寻找5.7文档引用的人:
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
是的,但只在innodb上。Innodb是目前唯一实现了外键的表格式。
As stated it does for InnoDB. At first I thought it was strange that many other (in particular MS SQL and DB2) doesn't. TableSpace scans are only better than index scans when there are very few table rows - so for the vast majority of cases a foreign key would want to be indexed. Then it kind of hit me - this doesn't necessarily mean it has to be a stand alone (one column) index - where it is in MySQL's automatic FK Index. So, may be that is the reason MS SQL, DB2 (Oracle I'm not sure on) etc leave it up to the DBA; after all multiple indexes on large tables can cause issues with performance and space.
推荐文章
- MySql: Tinyint (2) vs Tinyint(1) -有什么不同?
- 在Android SQLite中处理日期的最佳方法
- 如何在MySQL表中移动列?
- 在MySQL中选择最后一行
- 如何删除MySQL root密码
- Postgres唯一约束与索引
- MySQL对重复键更新在一个查询中插入多行
- 使用{merge: true}设置的Firestore与更新之间的差异
- mysql_connect():[2002]没有这样的文件或目录(试图通过unix:///tmp/mysql.sock连接)在
- 使用电子邮件地址为主键?
- MySQL:如何复制行,但改变几个字段?
- 不能删除或更新父行:外键约束失败
- MongoDB在v4之前不兼容ACID意味着什么?
- Mysql错误1452:不能添加或更新子行:外键约束失败
- MySQL DISTINCT在GROUP_CONCAT()上