如何根据其他行有条件地 select 行
How to conditionally select rows based on other rows
我有两个 table 具有简单的 1:n 关系。一个 table 包含成分及其可用性。另一个包含食谱及其各自的成分。
Table 食谱
RecipeA | IngredientA
RecipeA | IngredientB
RecipeB | IngredientA
RecipeB | IngredientC
和table成分
IngredientA | true
IngredientB | true
IngredientC | false
查询所有行的 table 配料可用的食谱是微不足道的。但是我如何 select 只有所有成分都可用的食谱?结果应该是
RecipeA
我想这可以用 ALL
运算符来完成,但我还没有成功。我试了没有成功
SELECT Recipe
FROM tblRecipes
WHERE Ingredient = ALL (
SELECT Ingredient
FROM tblIngredients
WHERE Available
)
一种方法使用聚合:
select r.recipe
from recipes as r inner join
ingredients as i
on r.ingredient = i.ingredient
group by r.recipe
having sum(iif(i.available = "false", 1, 0)) = 0;
sum()
正在计算给定食谱的 non-available 成分的数量。 = 0
表示 none“不可用”。
顺便说一句,数据模型的命名很糟糕。您应该有三个表:
Recipes
每个食谱一行。
Ingredients
每种成分一行。
RecipeIngredients
每个食谱中每种成分一行。
考虑使用 HAVING
条件的聚合查询,以根据可用成分计数检查配方计数。由于 True
boolean at -1.
的访问值,条件聚合乘以 -1
SELECT r.Recipe
FROM tblRecipes r
INNER JOIN Ingredient i
r.recipe = i.recipe
GROUP BY r.Recipe
HAVING COUNT(*) = SUM(i.available = 'true') * -1
我有两个 table 具有简单的 1:n 关系。一个 table 包含成分及其可用性。另一个包含食谱及其各自的成分。
Table 食谱
RecipeA | IngredientA
RecipeA | IngredientB
RecipeB | IngredientA
RecipeB | IngredientC
和table成分
IngredientA | true
IngredientB | true
IngredientC | false
查询所有行的 table 配料可用的食谱是微不足道的。但是我如何 select 只有所有成分都可用的食谱?结果应该是
RecipeA
我想这可以用 ALL
运算符来完成,但我还没有成功。我试了没有成功
SELECT Recipe
FROM tblRecipes
WHERE Ingredient = ALL (
SELECT Ingredient
FROM tblIngredients
WHERE Available
)
一种方法使用聚合:
select r.recipe
from recipes as r inner join
ingredients as i
on r.ingredient = i.ingredient
group by r.recipe
having sum(iif(i.available = "false", 1, 0)) = 0;
sum()
正在计算给定食谱的 non-available 成分的数量。 = 0
表示 none“不可用”。
顺便说一句,数据模型的命名很糟糕。您应该有三个表:
Recipes
每个食谱一行。Ingredients
每种成分一行。RecipeIngredients
每个食谱中每种成分一行。
考虑使用 HAVING
条件的聚合查询,以根据可用成分计数检查配方计数。由于 True
boolean at -1.
SELECT r.Recipe
FROM tblRecipes r
INNER JOIN Ingredient i
r.recipe = i.recipe
GROUP BY r.Recipe
HAVING COUNT(*) = SUM(i.available = 'true') * -1