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.
I assume you want a relational division query. See this question with a lot of ways to do this: How to filter SQL results in a has-many-through relation
There are also performance tests in @Erwin’s answer (for Postrgres) and you’ll notice that dynamic ways (using many Joins or many
EXISTSsubqueries or manyINsubqueries) perform faster than static queries with only a variable table or list.Test in your server, with your data to be sure though. MySQL for example has some performance issues with
INsubqueries, so I would expect it to perform faster with theJOINversions.Here’s the “Erwin 1” query, translated in your tables: