ORDER BY子句错误

时间:2012-03-17 16:07:05

标签: sql-server sql-server-2008

嘿伙计们,我在尝试运行查询时遇到此异常

  

restaurantData.restaurantId在选择列表中无效   因为它不包含在聚合函数或   GROUP BY子句。

查询:

SELECT 
    T1.restaurantId AS ID, 
    COUNT(T2.post_id) AS favCount 
FROM   
    restaurantData AS T1 
INNER JOIN 
    favoriteData AS T2 ON T1.restaurantId = T2.post_id 
ORDER BY 
    favCount DESC, ID DESC 

它说我必须添加ORDER BY子句中没有聚合的所有选择列,我已经为restaurantID做了这些。但它仍然给我错误。

2 个答案:

答案 0 :(得分:4)

您在查询中缺少GROUP BY T1.restaurantId

SELECT T1.restaurantId   AS ID, 
       COUNT(T2.post_id) AS favCount 
FROM   restaurantData AS T1 
       INNER JOIN favoriteData AS T2 
         ON T1.restaurantId = T2.post_id 
GROUP BY T1.restaurantId
ORDER  BY favCount DESC, 
          ID DESC 

如果您根本没有GROUP BY子句,那么这将为您提供整个源表的聚合(在这种情况下,选择列表中包含restaurantId无效而不将其包含在聚合中)而不是按照你明确的愿望分成餐厅。

答案 1 :(得分:4)

您正在使用聚合函数(COUNT),因此您还必须使用GROUP BY子句:

SELECT 
    T1.restaurantId AS ID, 
    COUNT(T2.post_id) AS favCount 
FROM   
    restaurantData AS T1 
INNER JOIN 
    favoriteData AS T2 ON T1.restaurantId = T2.post_id 
GROUP BY
    T1.restaurantID
ORDER BY 
    favCount DESC, ID DESC 

基本上,对于您的查询,您希望计算找到的行数 - 并且您希望结果分组restaurantId - 这就是GROUP BY子句表达的内容。