【问题标题】:How to add more columns in group by in db query builder or eloquent? [duplicate]如何在 db 查询生成器或 eloquent 中添加更多列? [复制]
【发布时间】:2018-05-31 19:53:15
【问题描述】:

我正在尝试使用 jobseeker_id 进行分组,现在我想在查询中选择更多列,这是我的查询...

$jobseekers =DB::table('calllogs')
    ->select(DB::raw('count(*) as user_count,jobseeker_id'))
    ->where('jobseeker_id', '<>', 1)
    ->whereNotNull('type_of_call')
    ->groupBy('jobseeker_id')  
    ->get();

calllogs表中有很多列,如id、jobseeker_id、type_of_call、status、call_reason等... 当前的上述查询只给我 user_count 和 jobseeker_id。我想添加 mroe 列,如 user_count、jobseeker_id、type_of_call、status、call_reason 等...

我尝试添加已经喜欢的

$jobseekers =DB::table('calllogs')
    ->select(DB::raw('count(*) as user_count,jobseeker_id,type_of_call,status,call_reason'))
    ->where('jobseeker_id', '<>', 1)
    ->whereNotNull('type_of_call')
    ->groupBy('jobseeker_id')  
    ->get();
dd($jobseekers);

结果相同。

非常感谢任何帮助。

【问题讨论】:

标签: mysql sql laravel


【解决方案1】:

所有非聚合列必须出现在 group by 子句中 -

select(DB::raw('count(*) as user_count,jobseeker_id,type_of_call,status,call_reason'))
             ->where('jobseeker_id', '<>', 1)
             ->whereNotNull('type_of_call')
             ->groupBy('jobseeker_id','type_of_call','status','call_reason')

【讨论】:

  • 这不会给我唯一的jobseeker_id,起初我有很多重复的jobseeker_id,所以我想按它们分组,
  • 那么你必须提供一些样本数据和预期的O/P。
  • 对不起兄弟,有没有办法这样做?这是分组的最佳解决方案吗?
  • Group by 子句的基本要求是“所有非聚合列必须出现在 Group By 子句中”,所以我认为没有其他方法可以实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2020-10-13
  • 2017-08-31
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
相关资源
最近更新 更多