有没有更有效的方法来编写这个存储过程?

时间:2014-10-04 19:43:14

标签: sql sql-server tsql

我是sql的新手,是否有更好的方法或更有效的方式编写我写的以下查询。我试图通过配方ID拉出所有配方类别,如果它们是联结表中配方ID的cateogy记录,则应返回true,否则返回false。

这里是一个食谱ID的预期输出的屏幕截图,你看到有些人有IsTagged True,有些人是假的

ScreenShot

SELECT Name AS TagName, Id AS TagID, 'false' AS IsTagged
FROM dbo.Category

EXCEPT 

SELECT category.Name AS TagName, category.ID AS TagID, 'false' AS IsTagged
FROM dbo.Category AS category
LEFT OUTER JOIN dbo.RecipeCategoryJunction AS junction
    ON junction.CategoryID = category.Id
LEFT OUTER JOIN dbo.Recipes AS recipe
    ON recipe.Id = junction.RecipeId
WHERE recipe.Id = 1019

UNION

SELECT category.Name AS TagName, category.ID AS TagID, 'true' AS IsTagged
FROM dbo.Category AS category
LEFT OUTER JOIN dbo.RecipeCategoryJunction AS junction
    ON junction.CategoryID = category.Id
LEFT OUTER JOIN dbo.Recipes AS recipe
    ON recipe.Id = junction.RecipeId
WHERE recipe.Id = 1019

1 个答案:

答案 0 :(得分:1)

你可以单独使用左连接来完成。

SELECT C.Name AS TagName, 
       C.Id AS TagID,
       (CASE WHEN junction.CategoryID is NULL then 'False' Else 'True') AS IsTagged
FROM dbo.Category C
LEFT JOIN dbo.RecipeCategoryJunction AS junction
    ON junction.CategoryID = category.Id
    junction.RecipeId =1019