开发者

Help writing a SELECT statement

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 an开发者_如何学Pythond became a huge mess. I want to keep it lean and mean.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜