mysql - Laravel DB raw 返回双倍总和

标签 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
    }
]

最佳答案

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

使用不同的方法:

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

关于mysql - Laravel DB raw 返回双倍总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52727105/

相关文章:

mysql - Grails 数据库逆向工程失败

sql - 如何根据另一个表的值获取一个表的最大值

mysql - 循环检查从一张表到另一张表的where条件

php - 如何在 Laravel 5 中仅对数据库表中的特定记录使用唯一验证?

mysql - 执行查询时出现 SQL 语法错误

android - Android 上的 HttpPost 崩溃应用程序

php - 使用数组获取提交表单操作

mysql - 设计一个字段有多个值的Mysql数据库

mysql - groupBy 期望多对多关系中有更多表列

php - Laravel Nova - 如何从 HasMany 字段中隐藏 'Create' 按钮?