我有以下查询:
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;
表格如下:
它应该返回时只返回一行的查询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)
您不能在联接中使用类似的聚合函数。您需要将其包装在子查询或其他内容中。