tags:

views:

31

answers:

1

Hi.

I'm fairly new to MySQL and don't know how to write a query I need for a personal project of mine.

I have three tables that need to be talked to in this query - books, tags, and books_tags (junction table).

The basic structure of them is fairly basic - books and tags both have an id column and a name column (in books it's called 'title' and in tags it's called 'tags'). The books_tags table has book_id and tag_id.

I want to be able to write a query which returns something like this

TITLE      | TAG
--------------------
BOOK ONE   | PHP
BOOK ONE   | MYSQL
BOOK ONE   | OOP
BOOK TWO   | CSS
BOOK TWO   | HTML
BOOK THREE | JAVASCRIPT

You get the idea. I was doing this using PHP loops and multiple queries but the query count got really high really fast and became a huge mess. I want to keep it lean and mean.

+4  A: 
select b.title, t.tag
from books b
inner join books_tags bt on b.id = bt.book_id
inner join tags t on bt.tag_id = t.id
order by b.title, t.tag

If you want to list books that have no tags as well, you can do this:

select b.title, t.tag
from books b
left outer join books_tags bt on b.id = bt.book_id
left outer join tags t on bt.tag_id = t.id
order by b.title, t.tag
RedFilter
Thanks again, RedFilter. Second time this week you've been able to help me with a query question. Do you happen to have a great MySQL book you'd recommend? I'm really itching to get better at this.
Marcus