【发布时间】:2018-08-17 08:24:30
【问题描述】:
我有这个 Eloquent 查询:
return DB::table('users')
->leftJoin('bet', function($join) use ($competition_id){
$join->on('users.id', '=', 'bet.user_id');
$join->on('bet.competition_id','=', DB::raw("$competition_id"));
})
->select('users.*', DB::raw('SUM(points) as score'))->get();
它返回一个错误:
SQLSTATE[42000]:语法错误或访问冲突:1140 如果没有 GROUP BY 子句( SQL:选择users.*, SUM(points) 作为来自users 的分数,在users.id 上左连接bet = bet.user_id 和bet.@987654330 @ = 1)
如果我只是将生成的 SQL(粗体)复制粘贴到 PhpMyAdmin 中,它可以完美运行...
您能帮我解决这个问题吗?因为这对我来说毫无意义......
谢谢
解决方案
问题只是缺少组:
return DB::table('users')
->leftJoin('bet', function($join) use ($competition_id){
$join->on('users.id', '=', 'bet.user_id');
$join->on('bet.competition_id','=', DB::raw("$competition_id"));
})
->select('users.*', DB::raw('SUM(points) as score'))->groupBy('users.id')->get();
解决方案 #2
根据 MySQL 的版本或配置,上述解决方案不起作用,我必须按照 Eric 的建议对所有字段进行分组:
return DB::table('users')
->leftJoin('bet', function ($join) use ($competition_id) {
$join->on('users.id', '=', 'bet.user_id');
$join->on('bet.competition_id', '=', DB::raw("$competition_id"));
})
->select('users.*', DB::raw('SUM(points) as score'))
->groupBy('users.id')
->groupBy('users.name')
->groupBy('users.firstName')
->groupBy('users.lastName')
->groupBy('users.email')
->groupBy('users.admin')
->groupBy('users.password')
->groupBy('users.remember_token')
->groupBy('users.created_at')
->groupBy('users.updated_at')->get();
}
【问题讨论】:
-
mysql 我假设?
-
你的 laravel 可能使用的是严格模式,而服务器默认没有。您可能需要添加
->groupBy('users.id)。 -
你有
SUM(),但我在你的声明中没有看到任何GROUP BY。 -
将所有非聚合列放入
GROUP BY。您的查询甚至不会在所有 dbms 中运行,除了MySQL。