使用Join with Where

时间:2014-12-16 16:09:40

标签: mysql join where-clause

我有以下表格。

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 =&#34; 1&#34;两次因为奶酪和面包。我需要修复查询,以便排除recipe.id =&#34; 1&#34;如果它有黄油(例如)

2 个答案:

答案 0 :(得分:5)

如果我理解你的问题,我认为你不想inner join。您可以使用outer join进行null检查,也可以使用not exists

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'
    )

答案 1 :(得分:3)

为确保包含Butter的食谱不在输出中,您可以使用包含LEFT JOIN条件的= 'Butter'。在主查询的WHERE子句中,您需要在IS NULL的列上查找ingredients,以确保您返回匹配。

SELECT recipe.id
FROM
  recipe
  -- Join condition specifically looks for 'Butter' (other ingredients may be chained with OR inside () )
  LEFT JOIN ingredients ON recipe.id = ingredients.recipe_id AND (ingredient = 'Butter')
WHERE
  (recipe.description LIKE '%CHEESE%' OR recipe.topic LIKE '%CHEESE%')
  AND (recipe.difficultylevel='Easy')
  AND (recipe.totaltime <= 30)
  -- NULL condition for matching ingredient
  AND (ingredients.ingredient IS NULL)

这是一个示范,返回1个符合您标准的食谱:http://sqlfiddle.com/#!2/73f975/1