views:

46

answers:

3

Hi there,

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?

+1  A: 

I would index both columns separately and yes you can eliminate the primary key.

Daniel A. White
Or make a compound PK.
Paulo Santos
A: 

If you are using such a "join-table", you'll probably use some joins in your queries -- and those will probably benefit from an index on each one of those two columns (which means two separate indexes).

Pascal MARTIN
+5  A: 

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.

Bill Karwin