Tags using JOINs
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
SELECT b.*,
t.name
FROM books b
INNER JOIN taggings t_b ON t_b.bookId_fk = b.id
INNER JOIN tags t ON t.id = t_b.tagId_fk
ORDER BY b.id
So, yes, it is possible.
Note: if you have the books without tags at all - change INNER
to LEFT
in both cases and you'll get the NULL
value instead of tag for that books.
精彩评论