MySQL是否自动索引外键列?
当前回答
是的,但只在innodb上。Innodb是目前唯一实现了外键的表格式。
其他回答
显然,一个索引是自动创建的,就像罗伯特发布的链接中指定的那样。
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和外键约束
如果你做ALTER TABLE(而不是CREATE TABLE),你不会自动得到索引,至少根据文档(链接是5.1的,但5.5也是一样的):
[…当您使用ALTER table向表添加外键约束时,请记住首先创建所需的索引。
这是不可能得到索引键自动使用
ALTER TABLE (NAME OF THE TABLE) ADD INDEX (FOREIGN KEY)
你创建的表的名称,例如photos和外键,例如照相_id。代码应该是这样的
ALTER TABLE photographs ADD INDEX (photograph_id);
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.
是的,但只在innodb上。Innodb是目前唯一实现了外键的表格式。
推荐文章
- HyperLogLog算法是如何工作的?
- 数据库和模式的区别
- 如何从命令行通过mysql运行一个查询?
- 如何从命令行在windows中找到mysql数据目录
- 如何找到MySQL的根密码
- 如何改变字符集(和排序)在整个数据库?
- mySQL:: insert到表,数据从另一个表?
- 重复键忽略?
- 将表从一个数据库复制到另一个数据库的最简单方法?
- 什么是分片,为什么它很重要?
- 如何通过查询在MySQL中获得数据库结构?
- MySQL删除表中的所有行,并将ID重置为零
- 在准备语句中使用“like”通配符
- MySQL中的表名是否区分大小写?
- 库未加载:libmysqlclient.16。在OS X 10.6上使用mysql2 gem运行'rails server'时出现dylib错误