我有一个SQL查询让我难过.基本上,我有一张Recipes
表(包括你毫无疑问的猜测)很多食谱.我有一张Ingredients
桌子,里面有各种各样的食材.我有一张RecipeIngredients
表将食谱与其使用的成分联系起来.最后,我有一张PopularIngredients
桌子(它实际上是一个视图,但是谁在乎?),其中包含了人们在厨房中最常用的成分:
CREATE Table Recipes
(
RecipeId int4,
Title varchar(100)
);
CREATE Table Ingredients
(
IngredientId int4,
Name varchar(100)
);
CREATE Table RecipeIngredients
(
RecipeId int4,
IngredientId int4,
Amount int2
);
CREATE Table PopularIngredients
(
IngredientId int4
);
Run Code Online (Sandbox Code Playgroud)
我的目标是获得仅使用流行成分的所有食谱清单.
可以在此处找到带有示例数据的SQL小提琴.
我正在寻找的是一个将返回鸡肉沙拉和煎饼的查询. Aligator Burgers不会退货,因为它使用的aligator不是一种流行的成分.
我尝试了一些涉及子选择和ALL
关键字的事情,但没有任何运气.我已经尝试了各种内部和外部连接,但只要其中至少一种成分受欢迎,配方行仍然会出现.任何帮助将非常感激!
我正在使用Postgres 9.1.
这将获得所有没有不在PopularIngredients表中的成分的食谱.
select * from Recipes r where not exists (
select * from RecipeIngredients ri
left join PopularIngredients pi on pi.IngredientId=ri.IngredientId
where ri.RecipeId=r.RecipeId and pi.IngredientId is null
)
Run Code Online (Sandbox Code Playgroud)
用于WHERE NOT EXISTS
确保PopularIngredients视图中没有遗漏任何成分:
SELECT R.*
FROM Recipes R
WHERE NOT EXISTS (
SELECT 1
FROM RecipeIngredients RI
LEFT JOIN PopularIngredients P ON P.IngredientId = RI.IngredientId
WHERE RI.RecipeId = R.RecipeId AND P.IngredientId IS NULL
)
Run Code Online (Sandbox Code Playgroud)
更新了您的SqlFiddle