Find a value which contains in ALL rows of a table

[亡魂溺海] 提交于 2019-12-13 20:17:57

问题


I need to select all values which are contained in ALL rows of a table.
I have table “Ingredient” and ProductIngredient(there I have a recipe of a product).
Ingredient

| ingredient_id | name | price | 
| 1             | Bla  | 100   
| 2             | foo  | 50

ProductIngredient.

| Product_id | ingredient_id
| 1          | 1   
| 1          | 2   
| 2          | 1

The output should be

|  1   |  Bla |  

as it is in all rows of ProductIngredient.

SELECT DISTINCT Ingredient_Id 
FROM Ingredients I
WHERE Ingredient_Id = ALL
    (SELECT Ingredient_id FROM ProductIngredient PI
     WHERE PI.Ingredient_Id = I.Ingredient_Id );

How can I fix my code to make it work?


回答1:


This will give you all Ingredients from I that are in PI for each product. This is assuming that each product does not have multiple rows for a product and ingredient combination.

SELECT I.Ingredient_Id 
FROM Ingredients I INNER JOIN ProductIngredient PI
     ON PI.Ingredient_Id = I.Ingredient_Id
GROUP BY I.Ingredient_Id
HAVING COUNT(*) >= (SELECT COUNT(DISTINCT Product_id) FROM ProductIngredient)


来源:https://stackoverflow.com/questions/47520068/find-a-value-which-contains-in-all-rows-of-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!