想象一个食谱数据库。共有三个表:
tbl_recipes、tbl_recipe_ingredients 和 tbl_ingredients。
成分可以是蔬菜或肉类。(ingtype 字段)
我需要有两个查询,一个是提取所有包含蔬菜和肉类的食谱,另一个是只提取蔬菜。
我一直在尝试这个查询,但它没有返回准确的结果数量。
SELECT DISTINCT tbl_recipes.title
FROM tbl_recipe_ingredients
INNER JOIN tbl_recipes ON tbl_recipe_ingredients.recipe_id = tbl_recipes.id
INNER JOIN tbl_ingredients ON tbl_recipe_ingredients.ingredient_id = tbl_ingredients.id
WHERE tbl_ingredients.ingtype = 'vegetable'
GROUP BY tbl_recipes.id
HAVING COUNT( DISTINCT tbl_ingredients.ingtype ) = 1
另一件不起作用的事情是,如果我将 Count 更改为 = 2(意味着每种成分类型中的一种或多种),我将得不到任何结果。
我认为这是 Top N 类型查询的一种变体,但我无法看到这个问题出在哪里。
我将不胜感激任何帮助。