Mysql 查找必须同时具有两个值而不是其中一个值的行

Mysql 查找必须同时具有两个值而不是其中一个值的行,mysql,Mysql,我需要找到同时具有两个值的行,例如: 找到所有必须包含面粉和糖的食谱,但通过我的查询,我得到了所有包含糖或面粉的食谱 我的问题是: select recipe_id, ingred_id from ingreds_values where ingred_id in (3,17) 我得到了这个结果 recipe_id| ingred_id 12083 | 3 12083 | 17 2990 | 17 10084 | 17 3046 | 17 5244

我需要找到同时具有两个值的行,例如:

找到所有必须包含面粉和糖的食谱,但通过我的查询,我得到了所有包含糖或面粉的食谱

我的问题是:

select recipe_id, ingred_id from ingreds_values where  ingred_id in (3,17)
我得到了这个结果

recipe_id| ingred_id
12083    | 3
12083    | 17
2990     | 17
10084    | 17
3046     | 17
5244     | 3
5244     | 17
但我需要得到这个结果:

recipe_id| ingred_id
    12083    | 3
    12083    | 17
    5244     | 3
    5244     | 17

如果您只是想要配方,我建议使用聚合和
拥有

select recipe
from ingreds_values
where ingred_id in (3, 17)
group by recipe
having count(distinct ingred_id) = 2;
如果您想要实际的行,您有几个选项。这个怎么样

select iv.*
from ingreds_values iv
where exists (select 1 from ingreds_values iv2 where iv2.recipe = iv.recipe and iv2.ingred_id = 3) and
      exists (select 1 from ingreds_values iv2 where iv2.recipe = iv.recipe and iv2.ingred_id = 17) and
      iv.ingred_id in (3, 17);

我相信DBA或其他人将能够为您创建一个更加优雅的查询,但这将实现以下目的:

select iv1.recipe_id, iv1.ingred_id, iv2.ingred_id
from
  ingreds_values iv1,
  ingreds_values iv2
where      
  iv1.recipe_id = iv2.recipe_id
  AND iv1.ingred_id in (3,17)
  AND iv1.ingred_id != iv2.ingred_id
  AND iv2.ingred_id in (3,17);

您的查询使用IN子句,该子句返回inred_值为3或17的任何行。但你需要的是既有3份记录又有17份记录的食谱。

谢谢。这就是我需要的。还有一个问题。当我有超过2种配料时,比如3或4种,那么我不确定如何实现您的解决方案?第一个示例仍然返回含有其中一种配料的配方,我只需要含有两种配料的配方。第二个例子非常慢,返回一个ingrident@gandrap . . . 第一个不能返回只有一种成分的配方,因为
having
子句保证有两种成分。这也很容易推广到更多的成分。