简体   繁体   English

我应该为多对多数据库表使用索引吗?

[英]Should I use indexes for a many-to-many database table?

does it make sense to create indexes for a table called user_movies with the following columns: 使用以下列为名为user_movies的表创建索引是否有意义:

user_id movie_id user_id movie_id

There will be much more reading than inserting or updating on this table but I'm not sure what to do. 在这张桌子上插入或更新会有更多的阅读,但我不知道该怎么做。 Also: Is it adequate to omit a primary key in this situation? 另外:在这种情况下是否足以省略主键?

The correct definition for this table is as follows: 该表的正确定义如下:

CREATE TABLE user_movies (
  user_id INT NOT NULL,
  movie_id INT NOT NULL,
  PRIMARY KEY (user_id, movie_id),
  FOREIGN KEY (user_id) REFERENCES users(user_id),
  FOREIGN KEY (movie_id) REFERENCES movies(movie_id)
) ENGINE=InnoDb;

Notice "primary key" is a constraint, not a column. 注意“主键”是约束,而不是列。 It's best practice to have a primary key constraint in every table. 最佳做法是在每个表中都有一个主键约束 Do not confuse primary key constraint with an auto-generated pseudokey column. 不要将主键约束与自动生成的伪键列混淆。

In MySQL, declaring a foreign key or a primary key implicitly creates an index. 在MySQL中,声明外键或主键隐式创建索引。 Yes, these are beneficial. 是的,这些都是有益的。

我会单独索引两列,是的,你可以消除主键。

I have always heard that you should create a unique index on BOTH columns, first one way ( user_id + movie_id ) then the other way ( movie_id + user_id ). 我一直听说你应该在BOTH列上创建一个唯一索引,首先是单向( user_id + movie_id ),然后是另一种方式( movie_id + user_id )。 It DOES work slightly faster (not much, about 10-20%) in my application with some quick and dirty testing. 通过一些快速而肮脏的测试,它在我的应用程序中的工作速度稍快(不多,大约10-20%)。

It also makes sure you can't have two rows that tie the same movie_id to the same user_id (which could be good, but perhaps not always). 它还确保你不能有两行将同一个movie_id到同一个user_id (这可能很好,但可能并不总是如此)。

如果您使用这样的“连接表”,您可能会在查询中使用某些连接 - 这些连接可能会受益于这两列中每一列的索引(这意味着两个单独的索引)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM