does it make sense to create indexes for a table called user_movies with the following columns:
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. 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
). It DOES work slightly faster (not much, about 10-20%) in my application with some quick and dirty testing.
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).
如果您使用这样的“连接表”,您可能会在查询中使用某些连接 - 这些连接可能会受益于这两列中每一列的索引(这意味着两个单独的索引)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.