2

I am having trouble getting my head around the following problem.

Given the following table structure and data, how might I select records that match two tags. For example:

+-----------------+------------------+
|  collection_id  |         tag      |
+-----------------+------------------+
|        1        |    advertising   |
|        1        |     tutorials    |
|        2        |    advertising   |
|        2        |       coding     |
+-----------------+------------------+

If I search for advertising && tutorials, it should return collection_id = 1, and not collection_id = 2.

Any pointers most welcome.

2
  • What you'd like to get: scalar collection_id? Or multiple values are possible? Commented Nov 14, 2012 at 8:11
  • I had a similar question at one point stackoverflow.com/questions/7492699/… In this case you would have a csv list of TAG's. Commented Nov 14, 2012 at 8:14

1 Answer 1

6
SELECT collection_ID
FROM tableName
WHERE tag IN ('advertising','tutorials')
GROUP BY collection_ID
HAVING COUNT(*) = 2

If unique constraint was not specified on the tag for each collection_ID

SELECT collection_ID
FROM tableName
WHERE tag IN ('advertising','tutorials')
GROUP BY collection_ID
HAVING COUNT(DISTINCT tag) = 2
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your help. I copied across more data, and it seems that the query isn't returning as I'd expected. Please see here > sqlfiddle.com/#!2/021e8/3/0
no, you have extra spaces on the tags see here (click here)
anyone care to explain about the downvote? :D thank you. much appreciated. (no pressure if you don't want hehe)

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.