0

i have problem with mysql query and i'm stuck...

I have post with many tags and i want to let users to get posts with choosen tags. I store information about tags in table like this:

Tag_warp(
id_tag_wrap,
id_tag,
id_post)

I need to select distinct post having selected tags. Do you have idea how to make it? If i ask for: id_tag = "5" AND id_tag= "2" i got no results (which is obvious) if i ask for: id_tag = "5" OR id_tag= "2" i have id_post with results having 2 or 5 but i need only those post having both id_tag.

Any advice?

2 Answers 2

3

You can group by post, and demand that each post has both tags:

select  id_post
from    tag_warp
where   id_tag in (2,5)
group by
        id_post
having  count(distinct id_tag) = 2
Sign up to request clarification or add additional context in comments.

Comments

0

You can do it like this:

SELECT * FROM Tag_warp
WHERE tag_id IN (2, 5)
GROUP BY post_id
HAVING COUNT(post_id) = 2

This will return posts that have both tags 2 and 5.

4 Comments

Without count(distinct ...), it will also return posts that have tag 2 twice
I was assuming that a post couldn't have twice the same tag
With a unique constraint on (tag_id, post_id) this would work fine
Yes, one post can't have same tag twice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.