【问题标题】:Error 1140 using the query builder of Laravel and count aggregate使用 Laravel 的查询生成器和计数聚合时出现错误 1140
【发布时间】:2020-05-08 09:38:04
【问题描述】:

我想使用 Laravel 查询生成器执行以下 SQL 查询:

select `source`, `customer_id`, COUNT(id) from `requests` where `source` = "ATC" and `customer_id` = 1234567

我尝试了以下代码,但它不能正常工作:

DB::table('requests')->select('source', 'customer_id', DB::raw('COUNT(id)'))->where('source', '=', 'ATC')->where('customer_id', '=', '1234567')->get();

我收到以下错误:

SQLSTATE[42000]: Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'opadidb.requests.source'; this is incompatible with sql_mode=only_full_group_by (SQL: select `source`, `customer_id`, COUNT(id) from `requests` where `source` = ATC and `customer_id` = 1234567)

可以帮忙吗?

【问题讨论】:

    标签: mysql sql laravel


    【解决方案1】:

    sum,count,min,max,avg 等聚合函数在与其他列一起选择时,必须为这些列之一添加 groupBy 子句。

    您的查询有两列 'source''customer_id' 您必须为它们添加一个分组依据:

    DB::table('requests')->select('source', 'customer_id', DB::raw('COUNT(id)'))
    ->where('source', '=', 'ATC')->where('customer_id', '=', '1234567')
    ->groupBy('source','customer_id')->get();
    

    【讨论】:

    • 嗯,在我的情况下,您的查询不起作用...我继续收到该错误。
    • 尝试像groupBy('customer_id','source')这样对两列进行分组。
    【解决方案2】:

    如果不对查询或 mysql 设置进行更改,您也无法按照消息中的说明运行第一个查询;

    在没有 GROUP BY 的聚合查询中,SELECT 列表的表达式 #1 包含非聚合列“opadidb.requests.source”。

    • 您更改 mysql 设置以启用ONLY_FULL_GROUP_BY,更多信息here

    • 您可以通过在末尾添加group by 子句将查询更改为类似的内容,具体取决于您想要达到的结果。

    • 如果已启用,则作为第三个选项,您可以更改 database.php 文件以将数据库的 strict 键从 true 更改为 false

    【讨论】:

      猜你喜欢
      • 2015-12-24
      • 2015-12-13
      • 2021-06-12
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 2019-04-18
      • 2016-10-07
      • 2018-08-03
      相关资源
      最近更新 更多