Ariyan
Ariyan

Reputation: 15158

Selecting a post and all of its tags from two table with a single Query

I have two tables; one with post data and in the other each row has a tag and post id (FK).
Is it possible to select a post with all of its tags from these two tables with a single Query? How?

Thanks

Upvotes: 0

Views: 80

Answers (2)

Anton Belousov
Anton Belousov

Reputation: 66

Assuming that you have tables named posts(id, content) and tags(post_id, tag):

SELECT posts.id, posts.content, tags.tag FROM posts 
    LEFT JOIN tags ON tags.post_id = posts.id
WHERE posts.id = ?

Upvotes: 2

charly
charly

Reputation: 956

I guess you could turn around the query

SELECT * FROM post p 
INNER JOIN TABLE tag
ON tag.tag_id = p.tag_id
WHERE p.post_id=?

Though I don't think that this will be quicker than doing 2 separate queries


EDIT

The comments below think it is quicker to do a join rather than two separate query.

Upvotes: 0

Related Questions