You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel使用DB::raw编写查询时groupBy失效无法统计答题次数如何解决

问题根因

你当前分组不生效的核心原因是groupBy中包含了单条答题记录独有的可变字段:number_of_correct_answers、user_scores.created_at,每个答题尝试的这两个字段值都不相同,会导致每一条记录被独立分为一组,最终统计出来的Attempts永远是1,无法合并统计同一用户同一测验的总答题次数。


修复方案

调整逻辑如下:

  • 分组仅保留测验维度固定字段 + 用户维度固定字段,排除每次答题会变化的字段
  • 所有可变字段都用聚合函数处理:答题次数用COUNT(),平均得分用AVG(),如果需要最新答题时间用MAX(),及格状态如果需要取最新结果可配合MAX()函数判断是否有过及格记录

修改后的代码示例:

$remarks = DB::table('user_scores')->where('quiz_id',$id)
    ->join('quiz_information','quiz_information.id', '=', 'user_scores.quiz_id')
    ->rightJoin('users','users.id', '=', 'user_scores.user_id')
    ->select(
        DB::raw('COUNT(user_scores.id) as Attempts'),
        'quiz_information.quiz_title AS `Quiz Title`',
        'quiz_information.total_points AS Points',
        'users.name AS Name',
        DB::raw('IF(MAX(remarks) = 1, "passed", "failed") as STATUS'),
        DB::raw("AVG(number_of_correct_answers) AS Average"),
        DB::raw('MAX(user_scores.created_at) AS `Last Attempt Time`')
    )
    // 仅保留固定维度字段分组,加主键避免同名字段分组错误
    ->groupBy('quiz_information.id', 'quiz_information.quiz_title', 'quiz_information.total_points', 'users.id', 'users.name')
    ->get()
    ->toArray();

return response([
    'message'=>"Remarks successfully shown", 
    'error'=>false,
    'error code'=>200,
    'line'=>"line".__LINE__."".basename(__LINE__),
    'quizRemarks'=>$remarks
], 200, [], JSON_NUMERIC_CHECK);

内容的提问来源于stack exchange,提问作者carlbarzon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 19:45:03