Search code examples
sqlruby-on-railspostgresqlrelational-division

How to select documents in SQL with at least N similar foreign keys


 doc.id|tag.id|taggings.id|    name

  3 |  3 |  3 | heroku
  3 |  4 |  4 | javascript
  3 |  5 |  5 | html
  4 |  4 |  6 | javascript
  4 |  3 |  7 | heroku
  4 |  5 |  8 | html
  4 |  6 |  9 | swagger

I have this table

I want to select elements that have at least N of the same tags,

so lets say documents that are tagged with html and heroku.

I would want to return doc 3 and doc 4 [in this table it would be the only two things in the table. lol but still!]


Solution

  • Here's one way with count and case:

    select id
    from documents
    group by id
    having count(case when name = 'html' then 1 end) > 0
       and count(case when name = 'heroku' then 1 end) > 0