Reputation: 5568
Is serialize the best way to do this?
If, say, I have a database of music and I want to classify music by genres. If I allow for multiple genres for a given album, do I store them as an array and serialize them? Like this?
$array = serialize(array(1,2,3));
// numbers are IDs of genres
I get that from another post here. I know I can unserialize them. What I don't get is how I would write an SQL statement that would retrieve some or all of the data. What would my SQL statement look like if I wanted to retrieve all of the genres for a given album?
Upvotes: 0
Views: 1620
Reputation: 1537
You're trying to model a many-to-many relationship (Music to Genre). So, you should create a separate table (Genre) and then a cross-reference table (Music_Genre) that has the IDs from the Music and Genre tables.
Upvotes: 2
Reputation: 15012
Don't.
For a many to many relationship, you need a third table:
songs: id, name, ...
genres: id, name, ...
relation_songs_genres: song_id, genre_id
Upvotes: 1
Reputation: 839124
You should normalize your database using an association table.
The Wikipedia article on first normal form has a good example involving people with multiple phone numbers.
Upvotes: 2
Reputation: 54445
You really want to normalise the data and store the genres and the album to genre association in different tables.
i.e.: You'd ideally have three tables:
By doing this you'll be able to trivially add/remove, etc. genres as required in the future and will be able to perform lookups by joining the tables rather than having to perform string manipulation.
Upvotes: 2
Reputation: 817128
It depends on what queries you want to run, but you should put the genres into its own table:
Genre
id | name
and create a table that associates albums with genres:
Album_Genre
album_id | genre_id
Upvotes: 4