查询将表中的行与数字列表进行匹配,按匹配的行数排序,并匹配标记并执行相同的操作?

时间:2014-03-18 01:39:12

标签: php mysql sql

我有一个食谱数据库。在这个数据库中,我有5个表:

- recipes
- ingredients
- ingredients_available
- tags
- tags_available

具有以下结构:

- recipes
id, name
- ingredients
id, recipe_id, ingredient_id
- ingredients_available
id, name
- tags
id, recipe_id, tag_id
- tags_available
id, name

我想用一组成分(这将是i.d数字)查询数据库,因此例如5,2,3并找到与这些数字部分或公正匹配的配方。然后我想按配料量订购食谱。我还想知道完成配方需要哪些其他成分以及相应的ingredient_id。我还希望查询中包含大量标签,因此只能找到与标签匹配的ingredient_id,并按匹配的标签数量再次排序。

如何创建这样的查询,也可以通过一个查询完成?我正在使用MySQL数据库。任何正确方向的指针都会很棒。谢谢。

2 个答案:

答案 0 :(得分:0)

我认为'加入'的力量来自这里。 我不确定你想要制作什么样的组合,但是我想到的是你在这里展示的结构:

//获取食谱配料

Select ingredients.* from recipe recipe
Inner Join ingredients ingredients on recipe.id = ingredients.recipe_id
order by ingredients.id

//获取食谱的可用成分

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

这是mysql的'join'概念的链接,用于解决您的问题:

http://dev.mysql.com/doc/refman/5.0/en/join.html

干杯!

答案 1 :(得分:0)

我设法通过以下查询完成了问题的第一部分:

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;
相关问题