sql group by count问题

时间:2009-12-08 22:56:00

标签: sql mysql

我有以下查询:

select d.restaurant_id, restaurant_category, dish_name, cuisine_id, count(ingredient_id)
  from restaurant r, dish d, composition c
 where r.restaurant_id = d.restaurant_id 
   and d.restaurant_id = c.restaurant_id 
   and d.dish_id = c.dish_id
group by d.restaurant_id
having count(distinct cuisine_id) > 1;

表格如下:

  • restaurant(restaurant_id,restaurant_category)
  • 菜(restaurant_id,dish_name,dish_id,cuisine_id)
  • 组成(restaurant_id,dish_id,ingredient_id)

它应该返回时只返回一行的查询3.任何想法?

3 个答案:

答案 0 :(得分:2)

建议#1,使用SQL92样式连接。 建议#2,在所有列名中使用别名 建议#3,如果你想要一个独特的cuisine_id然后成为聚合的一部分。

这里的主要问题是你的群组不正确。不属于聚合函数的所有列必须出现在GROUP BY子句中。我很惊讶您的数据库运行了这个。

以下是它的样子:

SELECT 
    d.restaurant_id, 
    cuisine_id, 
    Count(ingredient_id)  
FROM restaurant r
INNER JOIN dish d ON r.restaurant_id = d.restaurant_id
INNER JOIN composition c ON d.restaurant_id = c.restaurant_id AND d.dish_id = c.dish_id
GROUP BY d.restaurant_id, cuisine_id
HAVING Count(distinct(cuisine_id)) > 1

OR

SELECT 
    d.restaurant_id, 
    restaurant_category, 
    dish_name, 
    cuisine_id, 
    Count(ingredient_id)  
FROM restaurant r
INNER JOIN dish d ON r.restaurant_id = d.restaurant_id
INNER JOIN composition c ON d.restaurant_id = c.restaurant_id AND d.dish_id = c.dish_id
GROUP BY d.restaurant_id, restaurant_category, dish_name, cuisine_id, 
HAVING Count(distinct(cuisine_id)) > 1

如果您需要所有这些列,则需要将其作为子查询执行。

答案 1 :(得分:0)

如果是这个SQL Server,我会说你的GROUP BY子句有错误。尝试:

SELECT d.restaurant_id, restaurant_category, dish_name, cuisine_id, COUNT(ingredient_id)
FROM restaurant r, dish d, composition c
WHERE r.restaurant_id = d.restaurant_id
  AND d.restaurant_id = c.restaurant_id
  AND d.dish_id = c.dish_id
GROUP BY d.restaurant_id, restaurant_category, dish_name, cuisine_id
HAVING COUNT(DISTINCT cuisine_id) > 1;

答案 2 :(得分:-1)

您不能在联接中使用类似的聚合函数。您需要将其包装在子查询或其他内容中。