0

我有一个配置数据表,可以与食谱相关联(类别更通用)。

像这样:

食谱:

ID Name
1 Default
2 A
3 B

配置数据

ID equipment ParentID RecipeID
1  3420      1         1 
2  3420      1         2
3  3421      1         1
4  3421      1         2
5  3422      1         1

我想知道如何为配方“A”选择所有配置数据,如果配方 A 没有为配置数据行配置,则返回到“默认”值。然后我会得到这个:

ID equipment ParentID RecipeID
2  3420      1         2
4  3421      1         2
5  3422      1         1

我已经找到了类似的东西,但我不确定这是一个好方法:

select * from ConfigurationData
where RecipeID=2 and parentID=1
union 
select * from ConfigurationData
where RecipeID=1 and parentID=1
and Equipment not in (select Equipment from ConfigurationData 
where RecipeID=2 and parentID=1)
4

2 回答 2

0

像这样使用 CTE 的东西?

/** 
 * first declare an id to search for
 */
declare @recipeId int 

set @recipeId = 2 -- Change this to the recipe you want to select

/**
 * Now the actual query
 */
with cte as (
  select r.id as Recipe, c.id, c.equipment, c.recipeid, row_number() over (partition by r.id, c.equipment order by c.RecipeId desc) as row
  from
       recipes r inner join configuration c on r.id = c.recipeid or c.recipeid = 1
)
select
   id, equipment, recipeid
   from cte 
   where row = 1 
   and r.id = @recipeId
于 2013-05-21T09:03:32.263 回答
0
SELECT  cd.*
FROM    configurationData cdd
WHERE   recipeId = 1
LEFT JOIN
        configurationData cda
ON      cda.equipment = cdd.equipment
        AND cda.recipeId = 2
JOIN    configurationData cd
ON      cd.id = COALESCE(cda.id, cdd.id)
于 2013-05-21T09:09:24.063 回答