MySQL - 索引 innodb 外键

MySQL - indexing innodb foreign keys

在 InnoDB 中索引外键的性能有改进吗?据我所知 read,InnoDB 会自动为外键创建一个索引。

这是给我的创建 table.

的查询
DROP TABLE IF EXISTS `assignments`;

CREATE TABLE `assignments`
(
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `user` INTEGER NOT NULL,
    `job` INTEGER NOT NULL,
    `created_at` DATETIME,
    `updated_at` DATETIME,
    PRIMARY KEY (`id`),
    INDEX `job_fk1` (`user`),
    INDEX `job_fk2` (`job`),
    CONSTRAINT `job_fk1`
        FOREIGN KEY (`user`)
        REFERENCES `users` (`id`),
    CONSTRAINT `job_fk2`
        FOREIGN KEY (`job`)
        REFERENCES `jobs` (`id`)
) ENGINE=InnoDB;

在那里,他创建了名为 job_fk1 和 job_fk2 的外键。他用这些外键的名字作为索引的名字。

在 InnoDB 中索引外键的性能是否有所提高?

答案:不会。由于重复键,性能会下降。

你不需要

INDEX `job_fk1` (`user`),
INDEX `job_fk2` (`job`),

这些将由 InnoDB 内部自动创建。但是您需要在 users (id) 和 jobs (id) 上建立索引,以便在 assignments table[=17= 上进行更快的操作]

http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html

"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."

您是正确的,MySQL 将在创建外键约束时在列上创建索引(如果该列尚不存在)。但是,您可以随意在该列上创建索引,并根据需要删除自动生成的索引。

您可能还需要额外的多列索引来帮助查询,例如这个虚构的索引:

  SELECT id, user, job
  FROM assignments
  WHERE job = 5
  ORDER BY user

多列索引(job, user)既能满足查找又能排序,而且由于二级索引包含了主键,所以也起到了覆盖的作用本例中的索引。