Suppose we have two tables Foo and Bar. I have an association table Foo_Bar for a many-to-many relationship between Foos and Bars.
Now I basically want a query to select the Foos that match a dynamic number of Bar constraints. I could do this by dynamically generating a query with the proper number of joins:
SELECT *
FROM Foo F INNER JOIN
Foo_Bar FB1 ON FB1.FooId = F.Id AND FB1.BarId= Y INNER JOIN
Foo_Bar FB2 ON FB2.FooId = F.Id AND FB2.BarId= Z INNER JOIN
--one inner join for each constraint
I'm wondering if there's a simpler way. I basically want a query like this:
SELECT *
FROM Foo F
WHERE (Y, Z, ...) IN (SELECT BarId FROM Foo_Bar WHERE FooId = F.Id)
Of course that's not valid SQL, but I'm wondering if the dynamic query is the only reasonably portable way to achieve the desired result.