Mysql 在Laravel获得最佳成绩

Mysql 在Laravel获得最佳成绩,mysql,laravel,Mysql,Laravel,我有两张桌子: user: id, name score: id, user_id, point 现在我想得到5个用户名谁有最好的分数,但似乎它是错误的 这是我的密码: public function getTop(){ $top = DB::table('score') ->select('user_id', DB::raw('COUNT(point)')) ->groupBy('user_id')

我有两张桌子:

user: id, name

score: id, user_id, point
现在我想得到5个用户名谁有最好的分数,但似乎它是错误的

这是我的密码:

public function getTop(){
        $top = DB::table('score')
            ->select('user_id', DB::raw('COUNT(point)'))
            ->groupBy('user_id')
            ->orderBy(DB::raw('COUNT(point)'), 'DESC')
            ->take(5)
            ->get();
        return view('home',compact('top'));
    }

在您的情况下,数据库查询更有意义

数据库查询以获取总分前5名的用户id。 使用该结果联接用户表

$topResult = DB::table('users'
)->join(DB::raw('(SELECT user_id, SUM(point) as score FROM score GROUP BY user_id ORDER BY SUM(point) LIMIT 5) as top_scorer'), function($join) {
    $join->on('top_scorer.user_id', '=','users.id');
})
->select(['users.*', 'top_scorer.score']) //Select fields you need.
->orderBy('top_scorer.score')
->get();

在您的情况下,数据库查询更有意义

数据库查询以获取总分前5名的用户id。 使用该结果联接用户表

$topResult = DB::table('users'
)->join(DB::raw('(SELECT user_id, SUM(point) as score FROM score GROUP BY user_id ORDER BY SUM(point) LIMIT 5) as top_scorer'), function($join) {
    $join->on('top_scorer.user_id', '=','users.id');
})
->select(['users.*', 'top_scorer.score']) //Select fields you need.
->orderBy('top_scorer.score')
->get();
试试这个

DB::table('users')
    ->select(['users.id', DB::raw('MAX(sc.point) AS score')])
    ->join('score AS sc', 'sc.id', '=', 'users.id')
    ->groupBy('users.id')
    ->take(5)->get();
试试这个

DB::table('users')
    ->select(['users.id', DB::raw('MAX(sc.point) AS score')])
    ->join('score AS sc', 'sc.id', '=', 'users.id')
    ->groupBy('users.id')
    ->take(5)->get();

您得到的结果是什么?它返回前5名的每个用户的积分总和。我想要的是每个用户的最高分数,然后选择前5名用户,而不是count use max.@forpas这仍然是错误的。它成功返回了每个用户的最高点,但前5名是错误的。它成功返回了每个用户的最高点,那么它怎么可能是错误的?您是否将两个计数都更改为最大值?您得到的结果是什么?它返回前5名的每个用户的点数之和。我想要的是每个用户的最高分数,然后选择前5名用户,而不是count use max.@forpas这仍然是错误的。它成功返回了每个用户的最高点,但前5名是错误的。它成功返回了每个用户的最高点,那么它怎么可能是错误的?你把两个计数都改成最大值了吗?