Ok, I’ve run into the situation. 3 tables, tags, books, and the intersection table*. How do you deal with this again?
tags
-id int
-name varchar
books
-id int
-name varchar
taggings
-tagId_fk int
-bookId_fk int
Sample data
tags id name 1 good 2 really good 3 bad 4 long 5 exciting books id name 1 Pumpkin Man 2 O-castic Bastard taggings bookId_fk tagId_fk 1 1 1 4 2 4 2 5
So here Pumpkin Man has been tagged as good and long while O-castic Bastard has been tagged as long and exciting.
I want to write a single query that retrieves:
books.id books.name taggings.tagId_fk as tags.name (know what I mean?) 1 Pumpkin Man good 1 Pumpkin Man long 2 O-castic Bastard long 2 O-castic Bastard exciting
Not exactly what I want
SELECT DISTINCT taggings.bookId_fk, tags.name FROM tags INNER JOIN taggings ON taggings.tagId_fk=tags.tagId ORDER BY taggings.bookId_fk;
The question I really have is, is it even possible to display the above result in MySQL without:
- Breaking it into more than one query,
- Using a subquery at all?
*PS I know that some people don’t use an intersection table
So, yes, it is possible.
Note: if you have the books without tags at all – change
INNERtoLEFTin both cases and you’ll get theNULLvalue instead of tag for that books.