问题描述
$old_records = DB::connection("MysqL_old_s")->table('leads')
->select(DB::raw('count(*) as source_count,source'))
->groupBy('source')
->get();
dd($old_records); // works right
此查询正常运行。 我想再添加一列,例如 id 或 created_at 以选择
我无法做到以下几点:
$old_records = DB::connection("MysqL_old_s")->table('leads')
->select('id',DB::raw('count(*) as source_count,source'))
->groupBy('source')
->get();
dd($old_records); // it gives an error
sqlSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP
BY clause and contains nonaggregated column 'crmclini_crmv2.leads.id' which is not functionally
dependent on columns in GROUP BY
clause; this is incompatible with sql_mode=only_full_group_by (sql: select `id`,count(*) as
source_count,source,id from `leads` group by `source`)
解决方法
您应在group by子句中包括您选择的列,以对其进行分组:
$old_records = DB::connection("mysql_old_s")->table('leads')
->select('id',DB::raw('count(*) as source_count,source'))
->groupBy(['id','source'])
->get();
第二个选项(我不推荐),您可以在config / database.php中禁用only_full_group_by选项:
'connections'=> [ ...
'mysql' => [
...
'strict' => false,...
],]
除非有特殊情况,否则请按选择的列将查询分组