在laravel中处理phpMyAdmin返回错误的原始Mysql查询

在laravel中处理phpMyAdmin返回错误的原始Mysql查询,mysql,laravel,eloquent,Mysql,Laravel,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")); })

我有一个雄辩的疑问:

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组列混合MIN、MAX、COUNT、,。。。如果没有GROUP BY子句,则with NOT GROUP列是非法的SQL:select users.*,SUMpoints as GROUTS left join bet on users.id=bet.user_id和bet.competition_id=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();
}

我有很多问题,只有4个。原因是什么

你为什么不使用ORM?您应该尽可能利用该框架 为什么在$competition\u id上使用DB::raw?它只是一个插入到查询中的值 您可以在最终选择时使用selectRaw,以避免另一个DB::raw 很有可能是因为你的总数没有一个分组。您可以通过在MySql上放置GROUPBY或禁用strict模式来实现这一点 试试这个:

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

我猜是mysql?您的laravel可能使用严格模式,而服务器默认情况下不是。您可能需要添加->groupBy'users.id。您有SUM,但我在您的语句中没有看到任何GROUP BY。请将所有未聚合的列放在GROUP BY中。您的查询甚至不会在所有dbms中运行,可能除了MySQL。我在原始请求中使用$competition\u id,否则它似乎被视为一列:未知列“1”。你的查询几乎很好,我只需要修改一下select部分就可以了,看看我更新的帖子。谢谢很高兴你成功了!如果禁用严格模式,则不需要groupBy,尽管您应该这样做。这是因为:如果你要对一个专栏进行总结,mysql需要知道它的依据是什么:请随意将这个答案归类为一个解决方案,或者为未来的用户提供解决方案。有趣的是,这个请求取决于我开发应用程序的计算机,它仍然不能正常工作。我认为这与MySQL的版本和/或配置有关。请参阅我的更新答案以获得其他解决方案。再次感谢!