2016-06-22 44 views
2

我想知道是否有可能使用單個mysql查詢來完成某些操作,如果是這樣,那麼對最有效的方式感興趣做到這一點。SQL:返回具有給定項目的值的子集的項目的查詢

我有兩個字段的表...讓我們說配方成分

我正在尋找具有給定配方的成分的子集所有的食譜。

爲了說明:

Recipe | Ingredient 
------------------- 
sandwich | bread 

sandwich | lettuce 

sandwich | mustard 

sandwich | bacon 

sandwich | tomato 

bacon salad | lettuce 

bacon salad | tomato 

bacon salad | bacon 

veggie salad | lettuce 

veggie salad | tomato 

veggie salad | cucumber 

我傳遞「三明治」作爲參數,並需要一個查詢將返回培根沙拉(即成分都包含在夾層的列表成分),但不是蔬菜沙拉,因爲它含有黃瓜,這不在三明治中。

我查看了這個問題:

SQL query to exclude records that appear in other rows?

,但我認爲我的情況是不同的,更加複雜。如果我傳遞「培根」並排除所有包含「培根」以外的成分的食譜,這將是類似的,但我需要根據輸入配方成分的查詢生成我排除的內容列表。

希望有道理!我覺得這應該是相當平凡的,但我堅持。

TIA爲您提供幫助!

+0

我不知道你是否能在MySQL中做到這一點,但在SQL Server中,爲連接到子選擇,或者使用/ CTE定義,這將是微不足道的表 – Nikki9696

+0

謝謝,@ Nikki9696。你能爲我的例子建議一個SQLServer查詢嗎?我會看看它是否會與MySQL一起工作。 – Sofia

回答

0

可以說,表名是kitchen

select * from kitchen k0 where Recipe NOT IN 
(
select * from kitchen k1 where Recipe!="sandwitch" and 
ingredient NOT IN (select k2.ingredient from kitchen k2 where Recipe="sandwitch")) 

說明:

  • 查找具有ATLEAST一種成分是不是「sandwitch」的成分
  • 現在發現在菜譜食譜該表不在以上的配方集合中。
+0

謝謝!這也適用於一些調整。我認爲這比@Gordon Linoff快一點,但很難說,因爲我的桌子很小。 – Sofia

2

你想統計相同成分的數量。您可以使用left join和聚集做到這一點:

select i.recipe 
from ingredients i left join 
    ingredients i2 
    on i.ingredient = i2.ingredient and i2.recipe = 'sandwich' and 
     i.recipe <> i2.recipe 
group by i.recipe 
having count(*) = count(i2.ingredient); 

having子句會檢查所有成分有sandwich匹配。

+0

謝謝!!!!!我將不得不做一些測試,但我認爲這是完美:) – Sofia

0

可能是你需要一個內部聯接

select distinct a.Recipe 
from my_table as a 
inner my_table as b on a.ingredient = b.ingredient; 
0

這適用於SQL Server中。我相信有在MySQL中的等價

Drop Table #Test1 
Create Table #Test1 (Recipe Varchar(8000), Ingredient Varchar(8000)) 

Insert #Test1 Values ('sandwich', 'bread') 
Insert #Test1 Values ('sandwich', 'lettuce') 
Insert #Test1 Values ('sandwich', 'mustard') 
Insert #Test1 Values ('sandwich', 'bacon') 
Insert #Test1 Values ('sandwich', 'tomato') 
Insert #Test1 Values ('bacon salad ', 'lettuce') 
Insert #Test1 Values ('bacon salad ', 'tomato') 
Insert #Test1 Values ('bacon salad', 'bacon') 
Insert #Test1 Values ('veggie salad', 'lettuce') 
Insert #Test1 Values ('veggie salad', 'tomato') 
Insert #Test1 Values ('veggie salad', 'cucumber') 

;With cteQuery As 
(
Select T.*, A.Ingredient IngredientMatch 
    From #Test1 T 
    Left Join (
     Select Ingredient 
      From #Test1 
      Where Recipe = 'Sandwich' 
     ) A On A.Ingredient = T.Ingredient 
    Where Recipe != 'Sandwich' 
) 
Select Distinct Recipe From cteQuery Where Recipe Not In 
    (Select Recipe From cteQuery Where IngredientMatch Is Null) 
相關問題