Tamás Pap
Tamás Pap

Reputation: 18273

Select posts and tags in a single query

If I have 3 tables:

posts

post_id title body

tags

tag_id name

posts_tags

post_id tag_id

What is the best way to list (select) the posts and the tags for each of them from a single query?

Upvotes: 1

Views: 736

Answers (1)

tpolyak
tpolyak

Reputation: 1239

Simply join the three tables. If you use left join, you will also see which posts don't have tags.

SELECT *
FROM posts 
LEFT JOIN posts_tags ON posts.post_id = posts_tags.post_id
LEFT JOIN tags ON posts_tags.tag_id = tags.tag_id

Upvotes: 3

Related Questions