使用group by对2个表进行SQL查询

时间:2016-06-17 07:56:45

标签: mysql

我有两张桌子:

restaurant(id,name);
rating(id,rating,restaurant);

我正在做的是:

select 
    rt.name, avg(rg.rating) as rating
from
    restaurant rt,
    rating rg
where
    rg.restaurant = rt.id
group by rg.restaurant;

这是给我一张餐厅名称和每家餐厅的平均评分。我需要的还是没有评级的表的名称。

2 个答案:

答案 0 :(得分:0)

在评论中提及Matt尝试这个:

$a

答案 1 :(得分:-2)

SQL Fiddle

SELECT
restaurant.Name, avg(rating.Rating)
From restaurant
LEFT JOIN rating on rating.restaurant = restaurant.ID
GROUP BY rating.restaurant

尚无评级餐厅: SQL Fiddle

SELECT
restaurant.Name, avg(rating.Rating)
From restaurant
LEFT JOIN rating on rating.restaurant = restaurant.ID
GROUP BY rating.restaurant
HAVING     avg(rating.Rating) <=0