mysql – 使用Join和Where

我有以下表格.

Table Name: Recipe
id  topic    description    difficultylevel     totaltime
1   Cheese   Cheese         Easy                10
2   Cheese1  Cheese1        Medium              50

Table Name: Ingredients
id  recipeid    ingredient
1   1           Butter
2   1           Cheese
3   1           Bread

现在,当我运行以下查询时,它返回配方id =“1”,即使它不应该,因为我不想要一个含有黄油的配方.

SELECT recipe.id
FROM 
  `recipe`
  INNER JOIN ingredients ON recipe.id = ingredients.recipeid
WHERE 
  (recipe.description LIKE '%CHEESE%' OR recipe.topic LIKE '%CHEESE%')
  AND (recipe.difficultylevel='Easy')
  AND (recipe.totaltime <= 30)
  AND (ingredients.ingredient <> 'Butter')

由于奶酪和面包,它会两次返回recipe.id =“1”.我需要修复查询,以便它排除recipe.id =“1”,如果它有黄油(例如)

如果我理解你的问题,我认为你不想要内联.您可以使用带有空检查的外连接,或者可以使用不存在:

select id
from recipe r
where 
    (recipe.description LIKE '%CHEESE%' OR recipe.topic LIKE '%CHEESE%')
    AND (recipe.difficultylevel='Easy')
    AND (recipe.totaltime <= 30)
    AND not exists (
        select 1
        from ingredients i
        where r.id = i.recipeid
             and i.ingredient = 'Butter'
    )
相关文章
相关标签/搜索