-1

我有 2 张桌子 -AfricanRatingsAfricanRatingsAVG. AfricanRatingsAVG是查询的结果:

INSERT INTO AfricanRatingsAVG 
SELECT RecipeID, COUNT(*) AS Count, AVG(Rating) AS RatingAVG
FROM AfricanRatings
GROUP BY RecipeID

此查询工作正常,并AfricanRatingsAVG在新条目进入时更新AfricanRatings

使用了 GridView 控件,并且来自 AfricanRatingsAVG 的数据在 GridView 中显示得很好。我的问题:我还想从第三个表中获取数据,AfricanRecipes 也包含在同一个 GridView 中。我在 JOIN 之后尝试了 JOIN,但没有结果。尝试的最后两个 JOINS 是:

SelectCommand="SELECT * 
FROM (SELECT RecipeID, COUNT(*) AS Count, AVG(Rating) AS RatingAVG
FROM AfricanRatings
GROUP BY RecipeID  ) AS AfricanRatingsAVG
JOIN (SELECT AfricanRecipes.RecipeID, AfricanRecipes.Category, AfricanRecipes.Name, AfricanRecipes.Description
FROM AfricanRecipes
GROUP BY RecipeID  ) AS AfricanRecipes ON (AfricanRatingsAVG.RecipeID = AfricanRecipes.RecipeID)"

SelectCommand="SELECT * 
FROM (SELECT RecipeID, COUNT(*) AS Count, AVG(Rating) AS RatingAVG
FROM AfricanRatings
GROUP BY RecipeID  ) AS AfricanRatingsAVG
JOIN AfricanRecipes.RecipeID, AfricanRecipes.Category, AfricanRecipes.Name, AfricanRecipes.Description
FROM AfricanRecipes
GROUP BY RecipeID AS AfricanRecipes ON (AfricanRatingsAVG.RecipeID = AfricanRecipes.RecipeID)"

上面的第一个 JOIN 给出了错误消息:列AfricanRecipes.Category在选择列表中无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中。

第二个 JOIN 给出错误消息:

',' 附近的语法不正确

我已经尝试了上述连接的数十种变体,但都没有运气。任何帮助,将不胜感激。

4

1 回答 1

2
SELECT 
    AfricanRatingsAVG.*,
    AfricanRecipes.RecipeID, 
    AfricanRecipes.Category, 
    AfricanRecipes.Name, 
    AfricanRecipes.Description 
FROM (
    SELECT 
       RecipeID, 
       COUNT(*) AS RecipeCount, 
       AVG(Rating) AS RatingAVG 
    FROM AfricanRatings 
    GROUP BY RecipeID 
) AfricanRatingsAVG 
    JOIN AfricanRecipes
        ON AfricanRatingsAVG.RecipeID = AfricanRecipes.RecipeID
于 2013-03-04T22:08:12.857 回答