具体 SQL 问题:如何 select 所有 ID 匹配的行... (MySQL)

Specific SQL issue: How to select rows where ALL IDs match... (MySQL)

我有一个非常具体的问题,我什至无法决定如何处理。所以我在 MySQL 中有 3 个表。

Tablerecipe:id_recipe| name | text | picture

Table ingredients_recipe: id_rs | id_recipe| id_ingredients

Table ingredients: id_ingredient | name | picutre

这是一个站点,您可以在其中 select 成分(因此输入是 1 个或多个 id_ingredient),它应该显示三个类别:

  1. 你现在可以做的所有食谱(你有它所需的所有成分)
  2. 您只缺少 1 或 2 种成分的所有食谱
  3. 您只缺少 3 或 4 种成分的所有食谱。

你能帮我解决这 3 个 SQL select 问题吗?我现在很僵局。谢谢。

示例数据http://pastebin.com/aTC5kQJi

我认为你的基本陈述已经在正确的轨道上。你只需要做一个小技巧。不能直接比较,但是可以比较成分数:

SELECT id_receipe, count(id_rs) as ingredient_count 
   FROM ingredients_recipe 
   WHERE id_ingredient IN ( 2, 5) 
   GROUP BY id_recipe

这将为您提供每个收据的配料数量。现在获取每个收据的成分总量

SELECT id_receipe, count(id_rs) as ingredient_count 
   FROM ingredients_recipe 
   GROUP BY id_recipe

比较一下。以第一个查询为基础。你可以很容易地从中得到你的三个不同的类别。