[英]Match only if all elements of a column are in another table
I've made a little database in SQL that as 2 tables Product
( Name
, Ingredient
and Available
( Ingredient
): 我用SQL创建了一个小的数据库,该数据库作为2个表Product
( Name
, Ingredient
和Available
( Ingredient
):
| Product | Available |
| Name | Ingredient | Ingredient |
| 1 | a | a |
| 1 | b | c |
| 2 | a |
| 2 | c |
I want the name of a product only if ALL its ingredients are inside the Available
table. 仅当产品的所有成分都在“ Available
表中时,我才需要产品的名称。
For the previous example, the result should be: Product
"2" and not Product
"1", because I don't have the ingredient "b" in the Available
table. 对于前面的示例,结果应为: Product
“ 2”而不是Product
“ 1”,因为我在“ Available
表中没有成分“ b”。
Thanks for the help 谢谢您的帮助
You can try with left join
(to figure out which Products
don't have necessary Ingredients
) and group by
+ having
to filter Products
that have at least one missing Ingredient
: 您可以尝试left join
(找出哪些Products
没有必要Ingredients
)和group by
+ having
过滤Products
有至少一个缺少的Ingredient
:
select p.Name
from Products p
left join Available a on a.Ingredient = p.Ingredient
group by p.Name
having sum(a.Ingredient is null) = 0
You can try something like this also: 您也可以尝试以下操作:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.