mysql - 外键和索引

标签 mysql indexing foreign-keys

我有 2 个表:产品类别。每个类别有很多产品,一个产品可以属于多个类别。

产品

product_id - int primary auto increment
name - unique
etc.

类别

category_id - int primary auto increment
name - unique
etc.

我有一个 manyTomany 关系的第 3 个表。

产品类别

product_id -> foreign key: products.product_id
category_id -> foreign key: category.category_id

我的问题是:我是否应该为 product_categories 中的 product_idcategory_id 创建索引以加快选择查询,如果是,什么索引?

谢谢

最佳答案

这取决于哪些查询最频繁。

您最终可能会得到三个索引。

  1. 如果您有 ... WHERE products_categories.product_id = XXX,请在 product_id 上创建索引。

  2. category_id

    相同
  3. category_id product_id 上创建索引,如果您有 ... WHERE products_categories.category_id = XXX AND products_categories.product_id = YYY

然而,following the MySQL manual ,请记住 (category_id, product_id) 上的索引可能与 (category_id) 上的索引是多余的。同样,(product_id, category_id) 上的索引可能与 (product_id) 上的索引是多余的。因此,您最终可能会得到两个索引(而不是三个)来满足您所有的频繁查询需求。

关于mysql - 外键和索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8910431/

相关文章:

mysql - 从表中选择最适合特定区域设置的行

mysql - 如何在 Docker 容器中使用模式初始化 MySQL 数据库?

performance - 在 Postgres 中创建索引的最有效方法

python在groupby之后访问列

Android SQLite 外键语法错误

sql - 我应该使用 information_schema.referential_constraints 还是 sys.foreign_keys 来检查 key 的存在?

mysql - 将 SumIfs Excel 函数转换为 MySQL

mysql - MySQL如何在where函数中使用索引?

Oracle - 从子表中删除行锁定父表

javascript - Ajax - 单击按钮更新数据库