2014-06-20 45 views
0

我開始有一個頭痛的計算/搜索查詢來選擇所有匹配一些成分列表的菜餚。SQL選擇所有匹配成分標準的菜餚

我的表:

Ingredients 
============ 
ID 
IngredientName 
IngredientAmount 
P_ID 


Dishes 
========== 
ID 
DishName 


DishIngredients 
========== 
ID 
DishID 
IngredeientID 
IngredientAmount 

有即,兩個成分的名字,我想選擇所有的菜(所以我想知道他們的P_ID's)與給定的子集,我可以從它使(會有很多菜即5成分)

直到這一刻,我們有以下:

SELECT d.Name, i.IngredientName, di.IngredientAmount 
FROM Dishes AS d INNER JOIN DishIngredients AS di ON d.DishId = di.DishId 
INNER JOIN Ingredients AS i ON di.IngredientId = i.ID 
WHERE i.IngredientName IN ('salt','tomato') 

雖然這將表明,需要「西紅柿」的菜,但需要Ø其他成分,我們沒有列入清單。

+0

你可以分享你的餐桌結構嗎? – Mureinik

+0

嗨,可以請顯示「盤子」表的結構。 – Haris

+0

當然,在這裏。 – NightSnail

回答

0

我會做的是創建另一個表DishIngredients,與列DishIngredientIdDishIdIngredientId和移動IngredientAmount此表。
因爲,例如,多個菜可以有番茄作爲一種成分,但數量不同。

然後加入這三個表,以找出哪些菜有番茄作爲配料是這樣的:

SELECT d.Name, i.IngredientName, di.IngredientAmount 
FROM Dishes AS d INNER JOIN DishIngredients AS di ON d.DishId = di.DishId 
INNER JOIN Ingredients AS i ON di.IngredientId = i.IngredientId 
WHERE i.IngredientName = 'Tomato' 

(如果你要搜索一個以上的成分,使用IN條款,就像你已經做了)

我重讀你的問題,也許這就是你的意思(任何成分):

SELECT DISTINCT d.DishName 
FROM Dishes AS d INNER JOIN DishIngredients AS di ON d.DishID = di.DishID 
WHERE di.IngredientID IN (SELECT i.IngredientID 
FROM Ingredients AS i WHERE i.IngredientName IN ('Tomato', 'Cheese')) 

它列出了所有無濟於事以番茄和奶酪作爲配料。
參見本SQL Fiddle

如果你想所有成分,試試這個:

SELECT d.DishName, A.IngredientName, B.IngredientName 
FROM Dishes AS d 
CROSS APPLY (SELECT di.DishIngredientID, i.IngredientName FROM DishIngredients AS di 
    INNER JOIN Ingredients AS i ON di.IngredientID = i.IngredientID AND i.IngredientName = 'Cheese' 
    WHERE d.DishID = di.DishID) AS A 
CROSS APPLY (SELECT di.DishIngredientID, i.IngredientName FROM DishIngredients AS di 
    INNER JOIN Ingredients AS i ON di.IngredientID = i.IngredientID AND i.IngredientName = 'Tomato' 
    WHERE d.DishID = di.DishID) AS B 

對於每個額外的成分,添加其他CROSS APPLY

+0

好吧,我已經用你的建議重建了我的數據庫,儘管我的MySQL不喜歡你的語法:'因爲我在di.IngredientId ON i.IngredientId' - 第二個'ON'是意外的。 – NightSnail

+0

我已經編輯過以下查詢:SELECT d.Name,i.IngredientName,di.IngredientAmount FROM Dishes AS d INNER JOIN DishIngredients AS di ON d.DishId = di.DishId INNER JOIN成分AS i ON di.IngredientId = i.IngredientId 其中i.IngredientName IN('意大利麪條','西紅柿')'但是它不能做這項工作,因爲它顯示的菜餚包含番茄,但同樣的菜需要其他成分,沒有提供。 – NightSnail

+0

對不起,第二個'ON'是一個錯字,它確實需要一個'='。你可以通過'AND'和'OR'構造來添加成分。我會更新查詢以反映這一點。 – CoolWilly