【问题标题】:Raw Mysql query working on phpMyAdmin returning error in laravel在 phpMyAdmin 上工作的原始 Mysql 查询在 laravel 中返​​回错误
【发布时间】: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_idbet.@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

标签: mysql laravel eloquent


【解决方案1】:

我有很多问题,但 4. 是原因

  1. 您为什么不使用 ORM?您应该尽可能利用该框架
  2. 为什么 DB::raw 在 $competition_id 上?这只是您要插入到查询中的值
  3. 您可以在最终选择中使用 selectRaw 以避免另一个 DB::raw
  4. 很可能是缺少 groupBy(您的总和有问题)。您可以通过在 MySql 上放置 group by 或禁用严格模式来做到这一点

试试这个:

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

【讨论】:

  • 我在原始请求中使用 $competition_id ,否则它似乎被视为一列:(未知列'1')。您的查询几乎很好,我只需要更改一些选择部分即可使其工作(请参阅我更新的帖子)。谢谢!
  • 很高兴您可以使用它!如果您禁用严格模式,则不需要 groupBy(尽管您应该这样做)。这是因为:如果要对列求和,mysql 需要知道它是基于什么的:) 随意将此答案归类为解决方案或为未来用户提供解决方案
  • 这个请求的有趣之处在于,根据我正在开发我的应用程序的计算机,它仍然无法正常工作。我认为这与 MySQL 的版本和/或配置有关。请参阅我更新的答案以获得其他解决方案。再次感谢!
猜你喜欢
  • 2017-08-16
  • 2014-06-08
  • 2013-03-14
  • 1970-01-01
  • 2015-01-08
  • 1970-01-01
  • 2018-07-19
  • 2018-06-19
  • 2021-09-18
相关资源
最近更新 更多