Laravel 原始数据库 returns 双和

Laravel DB raw returns double sum

有两个 table:usersscore。分数 table 有列 game_idpoints.

这个查询

    return DB::table('users')
        ->where('users.id', 36)
        ->leftJoin('score AS education_score', function($query){
            $query->on('education_score.user_id', '=', 'users.id')
                ->where('education_score.game_id', 2);
        })
        ->leftJoin('score AS experience_score', function($query){
            $query->on('experience_score.user_id', '=', 'users.id')
                ->where('experience_score.game_id', 3);
        })
        ->groupBy(['users.id', 'users.name'])
        ->select([
            'users.name',
            DB::raw('SUM(education_score.points) AS education_score'),
            DB::raw('SUM(experience_score.points) AS experience_score'),
        ])
        ->get();

应该return

[
    {
        name: "JANE DOE",
        education_score: 70,
        experience_score: 2
    }
]

相反,它是 return 精确的双倍

[
    {
        name: "JANE DOE",
        education_score: 140,
        experience_score: 4
    }
]

您得到的结果不正确,因为您加入了同一个 table 两次。

使用不同的方法:

return DB::table('users')
    ->where('users.id', 36)
    ->leftJoin('score', 'score.user_id', '=', 'users.id')
    ->groupBy(['users.id', 'users.name'])
    ->select([
        'users.id',
        DB::raw('SUM(IF(score.game_id = 2, score.points, 0)) AS education_score'),
        DB::raw('SUM(IF(score.game_id = 3, score.points, 0)) AS experience_score')
    ])
    ->get();