2011-12-24 127 views
2

我有兩個表,CategoriesRecipeCategoriesSQL子查詢優化

**Categories** 
CategoryID varchar (Primary Key) 
Name varchar 

**RecipeCategories** 
RecipeID varchar 
CategoryID varchar 
Composite primary key 

我在尋找一種方式來回報類別ID和名稱的所有類別,配方以及是否實際屬於這一類。我可以使用類似

SELECT c.CategoryID, c.Name, 
     (SELECT COUNT(*) 
      FROM RecipeCategories 
      WHERE RecipeID = @recipeId AND CategoryID = c.CategoryID)) 
FROM Categories c 

但我不認爲如果表格變得太大,將會縮放。

回答

1
SELECT c.CategoryID 
    , c.Name 
    , Case When (r.RecipeID is null) Then 'No' Else 'Yes' End 
    FROM Categories c 
    left join RecipeCategories r on r.CategoryID = c.CategoryID 
           and r.RecipeID = @recipeId 
+0

AND而不是WHERE。有趣的解決方案,謝謝。 – Echilon 2011-12-24 16:55:09

+0

是的,'RecipeID = @ recipeId'必須處於連接狀態。否則,你只會得到一行。 – DavidEG 2011-12-24 17:08:03

0

您可以使用下面的示例,但爲了使此解決方案在大型環境中可伸縮,您需要索引RecipeID。

SELECT c.CategoryID, c.Name, count(rc.Composite) FROM Categories c 
LEFT JOIN RecipeCategories rc ON c.CategoryID = rc.CategoryID 
WHERE RecipeID = @recipeId 
GROUP BY c.CategoryID, c.Name;