1

I need to make a table 'Movies' which will have columns:

ID  Title  Description  Category etc

And another one called 'Movie_Categories' containing, for example

ID  Category
1   Action
2   Adventure
3   Triller

but since category in table Movies will have multiple choices what is the correct way to do this?

should i use comma-separated values like someone said in this post Multiple values in column in MySQL or is there a better way?

4

3 回答 3

3

This is a many-to-many relationship.

You need a join table to make it right, such as :

CREATE TABLE film_category (
  category_id int,
  film_id int,
  PRIMARY KEY (category_id, film_id)
);
于 2013-10-17T13:05:36.290 回答
1

DO NOT GO FOR COMMA-SEPARATED VALUES. NEVER.

Having said that. Bear in mind that when you have a so called many-to-many relationship, that is, a relationship where you can have one category with many movies and one movie with many categories, you will always need to generate an additional table.

This table will only need the Primary Keys of each of the other 2 tables and will have a compound key.

So the schema will end up being:

  • Movies(ID, Title, Description, Category)
  • Categories(ID, Category)
  • Movies_Categories(ID_Movie, ID_Category)

In bold are the primary keys.

In order to get all the categories for a movie you will just have to join each of the three tables.

A final comment about having multi-valued fields is that your table will not be in First Normal Form which will, sooner or later, give you lots of headaches.

于 2013-10-17T13:06:35.080 回答
0

The last thing to do is have a non normalized table by storing comma separated values. *You should have a table movies and a table for categories. You should create a mapping table which will map the movieId to the categoryId*

于 2013-10-17T13:06:25.780 回答