2

I have a system which tags files with text labels. Each file has several tags. The relevant tables/columns are:

taggings(fileHash,tagId)
tags(tagId,tagText)

How do I find all tagId which have both a row where tagText matches query 1 and another row where it matches query 2? In other words, how can I find each fileHash that has both of two tags when the tags are in separate rows as shown above?

Is there a way to do this for an arbitrary number of matches?

I found this which seems related, but when I try to write a query like that, I get an "Unable to prepare statement" error.

Sample Data

Taggings

fileHash    tagId
404ba9      1
404ba9      2
e04f90      1
e04f90      3

Tags

tagId       tagText
1           document
2           personal
3           work

Expected Result

If a user searched for both personal and document as defined in tags, return 404ba9 because both (404ba9, 1) and (404ba9,2) exist in taggings.

2
  • 1
    Sample data and expected results, please. A few rows will go a long way. Commented Jan 10, 2019 at 17:59
  • 1
    My question was answered, but I added sample data and expected results for anybody who comes across this post in the future. Commented Jan 16, 2019 at 15:11

1 Answer 1

3

I'd join the tables, have a condition on the tags, and count the number of matches:

SELECT   fileHash
FROM     taggings 
JOIN     tags ON taggings.tagId = tags.tagId
WHERE    tagText IN ('text1', 'text2')
GROUP BY fileHash
HAVING   COUNT(*) = 2
1
  • Thanks this worked great. I use SQL just rarely enough that I somehow didn't have to use HAVING until now. Commented Jan 16, 2019 at 14:59

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.