I have a table A with food products.
I have a table B with food addons.
Table B has the fields:
- price
- added_calories
- name
- products
I want to make such query that will get the top 10 (or more) combinations of product and addons that will result the best calories / price ratio . I need to keep the names of the addons and product to display to the user.
I should be able to have several addons on 1 product so that I should try and run through all combinations.
If we have addons a, b, c, d then I have to try the combinations:
- Product + a
- Product + b
- Product + ab
- Product + ac
- Product + ad
- Product + bc
- Product + bd
- …
Not every addon can be selected for each product. There’s an additional ‘connector’ table which indicates supported addons for a product.
Assuming that you want to maximize calories / price, I think this is doable. The trick is that, given a specific product, you’ll maximize calories / price by piling on add-ons, in descending order by calories / price ratio, until the total ratio starts to decrease.
The following query is probably ridiculously inefficient and in need of serious optimization, but at least it shows that a solution exists:
Edit: OK, I debugged it, now it actually works(!). Here’s some test data:
And results:
Edit 2: Oops, I had it maximizing price per calories instead of calories per price. Fixed.
Edit 3: The subqueries were ignoring the connector table. I’ve (hopefully) fixed that bug, but I haven’t been able to test it yet.