仅当列的所有元素都在另一个表中时才匹配

时间:2018-12-14 12:59:37

标签: mysql sql phpmyadmin

我已经在SQL中创建了一个小数据库,作为2个表ProductNameIngredientAvailableIngredient):

|     Product         | Available  |
|  Name  | Ingredient | Ingredient |
|   1    |      a     |      a     |
|   1    |      b     |      c     |
|   2    |      a     |
|   2    |      c     |

仅当产品的所有成分都在Available表中时,我才需要产品的名称。
对于前面的示例,结果应为:Product“ 2” 而不是Product“ 1”,因为我在Available表中没有成分“ b”。

感谢您的帮助

2 个答案:

答案 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;