简体   繁体   English

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

[英]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个表ProductNameIngredientAvailableIngredient ):

|     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.

相关问题 从一个表中选择所有元素,然后检查它们是否与另一个表匹配 - Select all elements from a table, and check if they match to another table 仅当一列与MYSQL中另一表的列中的值不匹配时才从一个表中选择值 - Selecting values from one table only if a column does not match the values in the column of another table in MYSQL MySQL匹配表列从另一个表的所有表相同的查询? - MySQL match table column from another table for all table with same query? 将列值与另一个没有公共列的表匹配 - Match column values with another table with no common column 仅当另一个表的所有条目都匹配某个条件时才更新 mysql 表 - Update mysql table only if all entries of another table match a certain condition 仅在与所有 get 元素匹配时才过滤数据 - Filtering data only if match with all get elements MYSQL仅在该表的列值与另一表的列值匹配的情况下,才如何从该表中选择数据? - MYSQL How do I select data from one table only where column values from that table match the column values of another table? 从表中进行选择,其中一个列仅包含来自另一列的元素 - SELECT from a table where a a column contains only elements from another column MySQL:匹配另一个表的所有记录 - MySQL: Match all records of another table MySQL删除所有匹配表列的单词 - MySQL Remove All Words that Match Table Column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM