我有 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_id
和 category_id
创建索引以加快选择查询,如果是,什么索引?
谢谢
最佳答案
这取决于哪些查询最频繁。
您最终可能会得到三个索引。
如果您有
... WHERE products_categories.product_id = XXX
,请在product_id
上创建索引。
相同category_id
在
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/