我正在尝试创建一个返回一组特定寄存器的查询,但我尝试了几种方法但它无法正常工作。
我有4张如下表:
recipe {
idRecipe integer,
name varchar(100)
}
recipeStep {
idStep integer,
idRecipe integer,
instruction varchar(100)
}
recipeIngredient {
idStep integer,
idIngredient integer
}
ingredient {
idIngredient integer,
name varchar(100)
}
过滤器将返回包含用户选择的成分的所有配方。让我们说我想要包含所有食谱内涵的所有食谱成分68,25,36,109。所以我来到这里:
SELECT r.*
FROM recipe r, recipeStep rs, recipeIngredient ri
WHERE r.idRecipe = rs.idRecipe
AND rs.idStep = ri.idStep
AND ri.idIngredient in (68,25,36,109)
问题是这个查询返回包含任何这些成分的所有食谱,我只想要包含所有食谱的所有食谱
答案 0 :(得分:2)
执行此操作的一种方法是使用group by
子句和having
子句,将组限制为具有4种不同成分的组。
SELECT r.idRecipe, r.name
FROM recipe r
JOIN recipeStep rs ON r.idRecipe = rs.idRecipe
JOIN recipeIngredient ri ON rs.idStep = ri.idStep
WHERE ri.idIngredient IN (68,25,36,109)
GROUP BY r.idRecipe, r.name
HAVING COUNT(DISTINCT ri.idIngredient) = 4;
或者,您可以跳过IN谓词并在having
子句中使用条件聚合:
SELECT r.idRecipe, r.name
FROM recipe r
JOIN recipeStep rs ON r.idRecipe = rs.idRecipe
JOIN recipeIngredient ri ON rs.idStep = ri.idStep
GROUP BY r.idRecipe, r.name
HAVING SUM(CASE WHEN ri.idIngredient = 68 THEN 1 END) > 0
AND SUM(CASE WHEN ri.idIngredient = 25 THEN 1 END) > 0
AND SUM(CASE WHEN ri.idIngredient = 36 THEN 1 END) > 0
AND SUM(CASE WHEN ri.idIngredient = 109 THEN 1 END) > 0;
只要配方有四个强制性配方,两个查询都会允许其他成分。如果你想要完全匹配,你可以在where子句中添加另一个条件。