mindstormsguy
Gawd
- Joined
- Nov 4, 2002
- Messages
- 654
I'm working on a project and I have a query i want to do on the database. I know how I could accomplish what i want using a couple queries and some php, but I much rather accomplish this task in one query.
I have a table like so:
Quite simply, this is what i want. Given a number of "ingredient_id"s, I want to return every unique "recipe_id" where every single row with that recipe_id has a matching ingredient_id with what was provided. In other words, I specify the ingredients I have, and i want to know which recipes i can make (without needing more ingredients).
The method I can think of that uses two queries and php is as follows:
which returns the number of total ingredients in each recipe
Which returns the number of ingredients I actually have for each recipe.
Now I could obviously process these two tables in php, to return each recipe_id where the counts are the same for both tables, but there must be a simple wya to get mysql to just return me that result directly, no?
I have a table like so:
Code:
mysql> select * from ingredients_link;
+-----------+---------------+
| recipe_id | ingredient_id |
+-----------+---------------+
| 1 | 2 |
| 1 | 8 |
| 1 | 9 |
| 2 | 18 |
| 2 | 1 |
| 3 | 7 |
| 3 | 6 |
| 7 | 2 |
| 7 | 19 |
| 7 | 22 |
| 7 | 26 |
| 7 | 12 |
| 7 | 23 |
| 7 | 20 |
| 7 | 21 |
+-----------+---------------+
Quite simply, this is what i want. Given a number of "ingredient_id"s, I want to return every unique "recipe_id" where every single row with that recipe_id has a matching ingredient_id with what was provided. In other words, I specify the ingredients I have, and i want to know which recipes i can make (without needing more ingredients).
The method I can think of that uses two queries and php is as follows:
Code:
mysql> select recipe_id,count(recipe_id) from ingredients_link group by recipe_id;
+-----------+------------------+
| recipe_id | count(recipe_id) |
+-----------+------------------+
| 1 | 3 |
| 2 | 2 |
| 3 | 2 |
| 7 | 8 |
+-----------+------------------+
which returns the number of total ingredients in each recipe
Code:
mysql> select recipe_id,count(recipe_id) from ingredients_link where ingredient_id = 2 or ingredient_id = 8 or ingredient_id = 9 group by recipe_id;
+-----------+------------------+
| recipe_id | count(recipe_id) |
+-----------+------------------+
| 1 | 3 |
| 7 | 1 |
+-----------+------------------+
Which returns the number of ingredients I actually have for each recipe.
Now I could obviously process these two tables in php, to return each recipe_id where the counts are the same for both tables, but there must be a simple wya to get mysql to just return me that result directly, no?