MySQL是否自动索引外键列?
当前回答
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.
其他回答
如果你做ALTER TABLE(而不是CREATE TABLE),你不会自动得到索引,至少根据文档(链接是5.1的,但5.5也是一样的):
[…当您使用ALTER table向表添加外键约束时,请记住首先创建所需的索引。
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提供了这个。你可以在foreign key子句后面加上一个外键名称,或者让MySQL为你创建一个名称。MySQL自动创建一个名为foreign_key_name的索引。
CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action
这是不可能得到索引键自动使用
ALTER TABLE (NAME OF THE TABLE) ADD INDEX (FOREIGN KEY)
你创建的表的名称,例如photos和外键,例如照相_id。代码应该是这样的
ALTER TABLE photographs ADD INDEX (photograph_id);
是的,但只在innodb上。Innodb是目前唯一实现了外键的表格式。
推荐文章
- 在PHP中插入MySQL时转义单引号
- 我如何得到“id”后插入到MySQL数据库与Python?
- 什么是ORM,它是如何工作的,我应该如何使用它?
- MySQL工作台:如何保持连接活动
- 'create_date'时间戳字段的默认值无效
- 为现有数据库生成ERD
- BASE术语解释
- 在表变量上创建索引
- 我可以从一个完整的mysql mysqldump文件恢复一个表吗?
- 计数在VARCHAR字段中字符串的出现次数?
- 非加密用途的最快哈希?
- 修改一个MySQL列为AUTO_INCREMENT
- 查询以列出数据库中每个表中的记录数量
- 如何删除数组元素,然后重新索引数组?
- 在ROR迁移期间,将列类型从Date更改为DateTime