I have a database of recipes. In this database I have 5 tables:
- recipes
- ingredients
- ingredients_available
- tags
- tags_available
With the following structure:
- recipes
id, name
- ingredients
id, recipe_id, ingredient_id
- ingredients_available
id, name
- tags
id, recipe_id, tag_id
- tags_available
id, name
I want to query the database with a set of ingredients (which would be there id numbers), so for example 5, 2, 3 and find recipes that match this numbers partially or impartially. I then want to order recipes by the amount of ingredients matched. I also want to know what other ingredients are needed to complete the recipe and there corresponding ingredient_id's. I also wish to an infinite amount of tags in to the query, and so only find ingredient_id's which match the tags and again order by the amount of tags matched.
How would I go about creating such a query, can also this be done with one query? I am using a MySQL database. Any pointers in the right direction would be great. Thank you.
I think the power of 'joins' come in here. I'm not sure what possible combinations you want to produce but here are some scenarios I think of with the structure you're presenting here:
//Get ingredients for recipes
Select ingredients.* from recipe recipe
Inner Join ingredients ingredients on recipe.id = ingredients.recipe_id
order by ingredients.id
//Get available ingredients for recipes
Select ingredients.* from recipe recipe
Inner Join ingredients ingredients on recipe.id = ingredients.recipe_id
Inner Join ingredients_available ingredients_available on ingredients.ingredient_id =
ingredients_available.id
order by ingredients.id
Here is a link to the 'join' concept of mysql to solve your questions:
http://dev.mysql.com/doc/refman/5.0/en/join.html
Cheers!
我设法通过以下查询完成了问题的第一部分:
SELECT recipes.*, COUNT(ingredients.id) AS occurences FROM recipes INNER JOIN ingredients ON recipes.id = ingredients.recipe_id WHERE ingredient_id IN (1, 3) GROUP BY recipes.id ORDER BY occurences DESC;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.