Mysql 查找与其他id相比其平均和最大的id

Mysql 查找与其他id相比其平均和最大的id,mysql,laravel,eloquent,Mysql,Laravel,Eloquent,我有一个名为Rating的MySQL表,其中包含id、rateable\u id、Rating、user\u id列。rateable_id是已评级记录的id,评级分数存储在评级星级中。我所要做的就是找到一个特定的应课差饷租值,它的平均总和在其他应课差饷租值中是最大的 在上面的示例表中,我应该得到应课差饷租值=26,因为与其他应课差饷租值相比,它的评级最大为3+3/2=3。 原始sql或雄辩的任何首选 编辑:很抱歉提到,但我已经做了粗略的非标准方式反正它返回的答案,但我正在寻找使用嵌套选择答案。

我有一个名为Rating的MySQL表,其中包含id、rateable\u id、Rating、user\u id列。rateable_id是已评级记录的id,评级分数存储在评级星级中。我所要做的就是找到一个特定的应课差饷租值,它的平均总和在其他应课差饷租值中是最大的

在上面的示例表中,我应该得到应课差饷租值=26,因为与其他应课差饷租值相比,它的评级最大为3+3/2=3。 原始sql或雄辩的任何首选

编辑:很抱歉提到,但我已经做了粗略的非标准方式反正它返回的答案,但我正在寻找使用嵌套选择答案。averageRating是计算评级的平均和的一个软件包$popular_post返回其平均评级总和最大的id


您需要选择2个选项:

SELECT MAX(rating) rating, rateable_id FROM (
    SELECT AVG(rating) rating, rateable_id FROM table GROUP BY reateble_id
) GROUP BY rateable_id ORDER BY rating LIMIT 1

我想这对你有点帮助

$ratings = Rating::all()->groupBy('rateable_id');

$topList = [];

foreach($ratings as $key => $value){
    $topList[$key] = ($value->sum('rating')) / count($value);
}

arsort($topList);                          //sort the array by top values
$max_rateable_id = key($topList);          //key of first item of the array
$max_rating = reset($topList);             //value of first item of the array
$both = [$max_rateable_id => $max_rating]; //key and value of the first item of the array 

到目前为止,你有没有尝试过解决这个问题?阅读这些关于分组和平均的链接@GiorgosBetsos我编辑了这篇文章,我试过,但不是用标准的方式。它工作正常,但不可靠。下次,请不要拍照,谢谢。相反,请看这绝对是在正确的道路上+1用于建议php循环上的查询逻辑。时间==$$
$ratings = Rating::all()->groupBy('rateable_id');

$topList = [];

foreach($ratings as $key => $value){
    $topList[$key] = ($value->sum('rating')) / count($value);
}

arsort($topList);                          //sort the array by top values
$max_rateable_id = key($topList);          //key of first item of the array
$max_rating = reset($topList);             //value of first item of the array
$both = [$max_rateable_id => $max_rating]; //key and value of the first item of the array