user967451
user967451

Reputation:

How should I store these multiple values in my MySQL table?

I'm designing the database for a new website where users can choose a number of their favorite music genres. Each genre has an id associated with it, so if John likes Pop, Rock and R&B he likes 1, 2 and 3.

What would be the best way to store these in the users table?

Right now I have them like this:

genre_id | user_id
------------------
1,2,3    | 1

and in the php I explode these values on the comma delimeter and grab the individual ids that way. But this is obviously not the right way to go about it.

I know I can have a seperate table called "genre_to_user" and for each genre John likes I can enter an entry into that table like so:

genre_id | user_id
------------------
1        | 1
2        | 1
3        | 1

And to get all the ones John likes I can do a SELECT * FROM 'genre_to_user where user_id = 1

But I don't think this would be very efficient in the long run, when that table gets filled with an immense number of records. And since I will be doing this calculation once for each user on listing pages where there are up to 30 users on the same page. And these pages are throughout the site.

So what would be the right (and efficient) way to go about this?

Additionally is there any datatype in mysql that was made to store comma separated values rather than just sticking them inside varchar field?

Upvotes: 0

Views: 414

Answers (2)

Craig Kohtz
Craig Kohtz

Reputation: 1

Creating a cross reference table like the genre_to_user you describe has the added benefit of allowing the search to be reversed. In other words, you can found out which users or how many users have a genre_id of 1.

Upvotes: 0

Richard
Richard

Reputation: 4415

You should use a cross reference table like the genre_to_user you describe. This is going to make it much faster for your database to search through the records.

Don't worry too much about "an immense number of records", that's what databases are for :-)

Upvotes: 3

Related Questions