still trying to get started in the world of databases, running into issues daily!
I have a table ‘songs’ which contains information on artists/tracks:
CREATE TABLE songs (
song_id INT AUTO_INCREMENT PRIMARY KEY,
artist_name varchar(100) DEFAULT NULL,
song_name varchar(100) DEFAULT NULL,
tag_fk SMALLINT,
FOREIGN KEY (tag_fk) REFERENCES tags(tag_id) ON DELETE SET NULL ON UPDATE CASCADE,
) ENGINE = 'InnoDB';
CREATE TABLE tags (
tag_id SMALLINT AUTO_INCREMENT PRIMARY KEY,
tag_name varchar(255) UNIQUE
) ENGINE = 'InnoDB';
Now I have a foreign key in ‘songs’ referencing ‘tags.tag_id’, ‘tags.tag_name’ will later contain tags like ‘lovesong’, ‘melancholic’. Now in certain cases a song can have more than one tag, so if its a melancholic lovesong it should have both tags. Though I just noticed I can not add two SMALLINT to tag_fk seperated by comma, it only allows one SMALLINT per row.
I figured I could add a new row to ‘tag.tag_name’ containing ‘lovesong;melancholic’ and later process it in php, splitting it by ‘;’, but that is rather a less sexy solution to the problem, especially because the data is added by a program and I would have to deal with sorting the strings, too, so I wouldn’t end up with duplicate tags like ‘lovesong;melancholic’ and ‘melancholic;lovesong’, which is basically the same.
How is that issue commonly solved? If I do replace ‘songs.tag_fk’ by a varchar column ‘songs.tag’ instead I will have tons of duplicate data, as there’s gonna be a lot of “Lovesongs” and “Melancholic” songs in the database, so a foreign key solution is probably best.
I also thought about adding ‘songs.tags_fk’ and ‘songs.tags_fk2’ but thats rather a dirty hack, too. Especially if some songs start having more than 2, 3, 4 tags.
What’s the best way to deal with that?
Sounds like a many-to-many relationship. You require a third table to link the two. So that one song can have many tags, and one tag can be assigned to many songs.
http://www.phpknowhow.com/mysql/many-to-many-relationships/