我开始头疼,查找/搜索查询以选择所有符合某些成分列表的菜肴。
我的桌子:
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 :(得分:0)
我要做的是创建另一个表格DishIngredients
,其中包含DishIngredientId
,DishId
,IngredientId
列,并将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
。