查找作为Id的SQL Server的逗号分隔列表的一部分的记录

时间:2015-11-29 06:14:34

标签: sql-server join

它有2个这样的表:

t_recipe

RecipeId        Name              InsertDate 
----------------------------------------------
1             Mutton            9/6/2015 0:00
2             Veg Biryani       9/5/2015 0:00

t_recipe_ingredient

RecipeId      IngrId          InsertDate
----------------------------------------------
1             200               9/6/2015 0:00
1             201               9/5/2015 0:00
1             101               9/4/2015 0:00
1             103               9/3/2015 0:00
2             100               9/2/2015 0:00
2             500               9/6/2015 0:00
2             501               9/5/2015 0:00
2             401               9/4/2015 0:00

我有一个存储过程,在IngrId参数中接受以逗号分隔的MyIngredientId列表,如下所示:

200,201,101,103,100,500,501

我必须得到所有可以从IngrId参数创建的食谱。与上面的示例一样,RecipeId = 1可以创建,因为它的所有成分都是MyIngredientId参数的一部分,但RecipeId = 2而不是IngrId = 401不在列表中。

我需要输出:

RecipeId         RecipeName
-----------------------------
1                Mutton

1 个答案:

答案 0 :(得分:0)

Marc_s是正确的,您应该尽可能使用Table-Valued Parameters,但是如果您想继续使用IN语句,可以使用Common Table Expressions执行类似的操作:

  ;WITH CTE
  as
    (
      SELECT r.RecipeID,COUNT(*) as NumIngredientsRequired
      FROM t_recipe r
        INNER JOIN t_recipe_ingredient i on   
              r.RecipeID = i.RecipeID
        GROUP BY r.RecipeID
        -- Output:
        -- RecipeID (1) NumIngredientsRequired (4)
        -- RecipeID (2) NumIngredientsRequired (4)
    ), x as
    ( 
      SELECT r.RecipeID,r.Name, COUNT(*) as Ingredients, cte.NumIngredientsRequired
      FROM t_recipe r
      INNER JOIN cte c 
            on r.RecipeID = c.RecipeID
      INNER JOIN t_recipe_ingredient i   
            on r.RecipeID = i.Recipe
      WHERE i.IngrID IN (200,201,101,103,100,500,501)
      GROUP BY r.RecipeID,r.Name, cte.NumIngredientsRequired
      -- Output: 
      -- RecipeID (1) Name (Mutton) Ingredients (4) NumIngredientsRequired (4)
      -- RecipeID (2) Name (Veg Biryani) Ingredients (2) NumIngredientsRequired (4)
  )
    SELECT x.RecipeID,x.Name
    FROM x 
    WHERE x.NumIngredientsRequired = x.Ingredients
    -- Output:
    -- RecipeID (1) Name (Mutton)