当DB具有复杂的PK表时,选择正确的数据

时间:2017-10-12 11:01:07

标签: sql sql-server tsql

我有一个食谱数据库。但我们只需看3个表:

[Recipe]
ID (PK)
Name
<...>


[RecipeIngredient]
IDRecipe
IDIngred
Quantity
(IDRecipe, IDIngred) - PK

[Ingredient]
ID (PK)
Name
Units

所以我想得到一个类似于

的食谱名称的表格
[Name]    [Quantity]    [Units]
ingr1        50           gr.
ingr2        100          ml.
ingr3        1            kg.

我的查询是

SELECT [Name], [Quantity], [Units] FROM [Ingredient], [RecipeIngredient] 
WHERE [ID] = ANY
    (SELECT [IDIngred] FROM [RecipeIngredient] WHERE [IDRecipe] = 
    (SELECT [ID] FROM [Recipe] WHERE [Name] = 'RecipeName1'));

但我得到的是

[Name]    [Quantity]    [Units]
ingr1        50           gr.
ingr1        100          ml.
ingr1        1            kg.
ingr2        50           gr.
ingr2        100          ml.
ingr2        1            kg.
ingr3        50           gr.
ingr3        100          ml.
ingr3        1            kg.

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

尝试此查询:

SELECT I.[Name], RI.[Quantity], I.[Units] 
    FROM [RecipeIngredient] AS RI
        LEFT JOIN [Recipe] AS R ON R.ID = RI.IDRecipe
        LEFT JOIN [Ingredient] AS I ON I.ID = RI.IDIngred
    WHERE R.Name = 'someRecipeName'

答案 1 :(得分:0)

尝试以下查询:

SELECT Rec.Name, Ing.Name, Quantity, Units 
FROM Ingredient Ing
Inner Join RecipeIngredient Ri
on Ri.IDIngred  = Ing.ID
Inner Join Recipe Rec
on Rec.ID = Ri.IDRecipe
WHERE Rec.ID IN
            (Select distinct ID from Recipe);

上述查询会逐一返回特定食谱的名称和特定食谱的成分详情。

希望它有所帮助!