Search code examples
sqldatabasemany-to-many

Many-to-many sql select query containing multiple values, all values are taken into account


There is the following database structure:

enter image description here

How do I write a query that returns only those Questions that have both CSS and JS tags?


Solution

  • You can use aggregation and having:

    select tq.question_id
    from tagsquestions tq join
         tags t
         on tq.tag_id = t.id
    where t.name in ('JS', 'CSS')
    group by tq.question_id
    having count(*) = 2;
    

    This assumes that the tags assigned to a single question are distinct. That seems like a reasonable assumption.