i have a database where i cannot figure out how to fetch the book data. i’ll be explaining how i did it before and how i plan to do it now.
to make it simple, i’ll take the “books” example since it’s the easiest to show the relationship. before, i had this structure which i found heavy on the DB:
Books:
book_id
title
author_name
genre_name
it was easy to query individual books, all books, books by author and books by genre. the problem here was when i need to get the list of authors or genres. i had to select ALL books, detect possible duplicates, identicals, uniques etc. before handing them over to the browser. i already felt the lag in processing.
so what i plan to do now is this: i have 3 tables, one for books, another for authors and another for genres.
Books: Authors: Genre:
book_id author_id genre_id
title author_name genre_name
author_id
genre_id
this way, i can tag the books by author_id and genre_id as well as easily get all authors and genres more quickly without affecting the “get by author” and “get by genre”. Also, i can easily change the book author and/or genre by altering author_id and genre_id.
but if i select a book, how do i do it when the normal select * from Books where book_id=something returns only the ids of genres and authors? how do i do it to return author names and genre names? subquery? a separate query? or is there actually a one-liner query that i don’t know about?
You need to use a INNER JOIN so you could do something like this
As an alternative if you did not want to create separate tables (which is good design by the way) you could use a DISTINCT query