我已经在SQL中创建了一个小数据库,作为2个表Product
(Name
,Ingredient
和Available
(Ingredient
):
| Product | Available |
| Name | Ingredient | Ingredient |
| 1 | a | a |
| 1 | b | c |
| 2 | a |
| 2 | c |
仅当产品的所有成分都在Available
表中时,我才需要产品的名称。
对于前面的示例,结果应为:Product
“ 2”
而不是Product
“ 1”,因为我在Available
表中没有成分“ b”。
感谢您的帮助
答案 0 :(得分:1)
您可以尝试使用left join
(找出哪些Products
不需要Ingredients
)和group by
+ having
来过滤{{1 }}至少缺少一个Products
:
Ingredient
答案 1 :(得分:0)
您也可以尝试以下操作:
WITH TEMP_PRODUCTS AS
(
SELECT NAME, COUNT(1) AS NUMBER_OF_INGREDIENTS
FROM PRODUCT
GROUP BY PRODUCT
)
SELECT PRD.NAME, COUNT(1) AS NUMBER_OF_AVAILABLE_INGREDIENTS
FROM PRODUCT PRD
JOIN TEMP_PRODUCTS TMP ON PRD.NAME = TMP.NAME
WHERE EXISTS (SELECT 1
FROM INGREDIENT ING
WHERE ING.INGREDIENT = PRD.INGREDIENT)
GROUP BY PRD.NAME
HAVING COUNT(1) = TMP.NUMBER_OF_INGREDIENTS;