Laravel DB原始回报双倍总和

时间:2018-10-09 18:17:29

标签: mysql database laravel-5 laravel-5.5

有两个表:usersscore。得分表包含列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();

应该返回

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

相反,它返回的是精确的double

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

1 个答案:

答案 0 :(得分:1)

由于两次连接同一张表,所以结果不正确。

使用其他方法:

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();