We have a table of plans and each plan has many services. We would like a fast way of finding the combinations of plans that do not contain duplicate services but as a combinations contain certain services.
e.g. table of plans
id | service_1 | service_2 | ...
---------------------------------
1 | true | true | ...
2 | true | false | ...
3 | false | true | ...
e.g. valid combinations containing service_1 and service_2
UPDATE
If there were 2 services and I required both of them we would combine up to 2 rows (or plans) as they could contain at minimum 1 service in each.
id | service_1 | service_2 | id | service_1 | service_2 |
---------------------------------------------------------
1 | true | true |NULL| NULL | NULL |
2 | true | false | 3 | false | true |
UPDATE
It currently works by self left joining itself with aggressive pruning or rows. The query is dynamically generated based on the number of services. It creates the permutations of valid join conditions making it not practical to post.
Currently the cost is in the order of number of plans ^ number of services.
I’m mostly interested in other ways of solving this not necessarily improvements to the current way.
This seems to work ok
Setup data
The query
Result