here are 5 rows of my column Genres in my table data
Classics, Fiction, Historical Fiction, School, Literature, Young Adult, Historical
Fantasy, Fiction, Young Adult, Magic, Childrens, Middle Grade, Classics
Classics, Fiction, Romance, Historical Fiction, Literature, Historical, Audiobook
Classics, Nonfiction, History, Biography, Memoir, Historical, Holocaust
Classics, Fiction, Dystopia, Fantasy, Politics, School, Literature
What syntax should i use to make sure that all rows only have either values:
Classics, Fiction, Literature, Young Adult, Fantasy
i am currently lost and all suggested solutions from the internet have resulted to nothing
2
Answers
Here’s a solution:
Demo using MySQL 8.0: https://dbfiddle.uk/XpPxmhX1
The better solution is to store each genre in a separate row of a second table. This is a standard way to store many-to-many relationships.
Re your comment:
If the ordering is significant, then I suppose the potential duplicates are also significant.
There could be a solution, but the more important point is that there shouldn’t have to be.
Store the data in a normalized fashion, and it will be a lot easier. You won’t have to solve hard problems like manipulating comma-separated lists.
Here’s an example:
This stores one genre value per row, and only the values currently enumerated by the
genres
table. You can store them in any order you want in thedata_genre
table. It also permits duplicates if that’s desired.If you want to change the list of genres, then add or remove a row to the
genres
table.A normalized table could look like:
and used like this:
see: DBFIDDLE