Search code examples
sqlsql-servert-sqlinner-joinrelational-division

JOIN of 2 tables where cross all records


Given these 2 tables

Table name: MyValues

Id IdValue
1 10
2 10
3 10
1 11

Table name: MyConditions

Id IdValue
7 10
7 11

How could I write a query to get the Ids from the MyValues table to return the ones that match all the records on MyConditions table where MyValues.IdValue = MyConditions.IdValue

So the result would be 1 (since Id 1 from MyValues table matches all records in MyConditions table)


Solution

  • This reads like a relational division problem. We can join, and filter with having:

    select v.id
    from myvalues v
    inner join myconditions c on c.idvalue = v.idvalue
    group by v.id
    having count(*) = (select count(*) from myconditions)
    

    This assumes no duplicate (id, idvalue) in myvalue, and no duplicate idvalue in mycondition. Otherwise, we would typically use distinct on one or both side of having:

    having count(distinct v.idvalue) = (select count(distinct idvalue) from myconditions)