Laravel-嵌套选择(口才)

时间:2020-02-25 04:54:04

标签: sql laravel eloquent

我有一个成绩表,我必须将其按try_number分组并取总和 我想使用Eloquent和SQL raw嵌套此查询,并从尝试中获取最大分数,并根据分数对它进行排序。我需要最终结果作为排行榜。

  $usersByScore =  Attempt::where('game_id',$id)
    ->select('user_id','attempt_no','game_id',DB::raw('SUM(score) as total_score'))
    ->groupBy('attempt_no')
    ->orderBy('total_score', 'DESC')
    ->get()

这给了我排行榜,但它有用户的所有尝试。我只需要为按分数降序排列的每个用户尝试最大分数即可。

2 个答案:

答案 0 :(得分:0)

为此使用distinct()方法:我希望它会起作用。

$usersByScore =  Attempt::where('game_id',$id)
    ->select('user_id','attempt_no','game_id',DB::raw('SUM(score) as total_score'))
    ->groupBy('attempt_no')
    ->orderBy('total_score', 'DESC')
    ->distict()
    ->get()

答案 1 :(得分:0)

解决方案-实现了from方法来嵌套查询

$usersByScore =  Attempt::with('user')
        ->select(DB::raw('MAX(tscore) as total_score, user_id,attempt_no'))
        ->from(DB::raw('(SELECT user_id,attempt_no,SUM(score) as tscore FROM 
         attempts WHERE game_id = '.$id.' GROUP By attempt_no,user_id) AS T'))
        ->groupBy('user_id')
        ->get();