SQL:Select条条目中"reviews"条的数量最多,然后按平均条数最高的条数排序
SQL: Select entries with the biggest amount of "reviews" and then order the result by the highest average rate of them
我有以下代码:
select
count(restaurants.id) as restaurant_count,
`restaurants`.*,
round(AVG(restaurant_reviews.rate), 1) as rate
from
`restaurants`
inner join `restaurant_reviews` on `restaurant_reviews`.`restaurant_id` = `restaurants`.`id`
group by
`restaurants`.`id`
order by
`restaurant_count` desc
limit
3
这个returns我是这样的:
restaurant_count, id, name , rate
25 , 12, Restaurant 12, 4.6
22 , 08, Restaurant 08, 4.1
17 , 19, Restaurant 19, 4.4
这意味着它 returns 拥有最多 restaurant_reviews
数量的前 3 家餐厅(评论数量显示在 restaurant_count
)。
我想要实现的是,之后,按比率降序排列这些结果。例如:
restaurant_count, id, name , rate
25 , 12, Restaurant 12, 4.6
17 , 19, Restaurant 19, 4.4
22 , 08, Restaurant 08, 4.1
我该怎么做?我在 SQL 中写了所有内容,但也欢迎 laravel 查询构建器。
我尝试简单地将 order by
更改为:
order by
`restaurant_count` desc,
`rate` desc
limit
3
但它会先按 restaurant_count
排序,之后只会按比率对具有相同数量 restaurant_count
的条目排序。这意味着每家拥有最大 restaurant_count
的餐厅将始终处于更高的位置,无论其价格如何。这就是问题。
使用子查询:
select r.*
from (select count(*) as review_count, r.*, round(avg(rr.rate), 1) as rate
from restaurants r join
restaurant_reviews rr
on rr.restaurant_id = r.id
group by r.id
order by review_count desc
limit 3
) r
order by rate desc;
我有以下代码:
select
count(restaurants.id) as restaurant_count,
`restaurants`.*,
round(AVG(restaurant_reviews.rate), 1) as rate
from
`restaurants`
inner join `restaurant_reviews` on `restaurant_reviews`.`restaurant_id` = `restaurants`.`id`
group by
`restaurants`.`id`
order by
`restaurant_count` desc
limit
3
这个returns我是这样的:
restaurant_count, id, name , rate
25 , 12, Restaurant 12, 4.6
22 , 08, Restaurant 08, 4.1
17 , 19, Restaurant 19, 4.4
这意味着它 returns 拥有最多 restaurant_reviews
数量的前 3 家餐厅(评论数量显示在 restaurant_count
)。
我想要实现的是,之后,按比率降序排列这些结果。例如:
restaurant_count, id, name , rate
25 , 12, Restaurant 12, 4.6
17 , 19, Restaurant 19, 4.4
22 , 08, Restaurant 08, 4.1
我该怎么做?我在 SQL 中写了所有内容,但也欢迎 laravel 查询构建器。
我尝试简单地将 order by
更改为:
order by
`restaurant_count` desc,
`rate` desc
limit
3
但它会先按 restaurant_count
排序,之后只会按比率对具有相同数量 restaurant_count
的条目排序。这意味着每家拥有最大 restaurant_count
的餐厅将始终处于更高的位置,无论其价格如何。这就是问题。
使用子查询:
select r.*
from (select count(*) as review_count, r.*, round(avg(rr.rate), 1) as rate
from restaurants r join
restaurant_reviews rr
on rr.restaurant_id = r.id
group by r.id
order by review_count desc
limit 3
) r
order by rate desc;