sql - Laravel - 嵌套选择(雄辩)
问题描述
我有一个分数表,我必须按尝试编号分组,并获取我想使用 Eloquent 和 SQL 原始嵌套此查询的分数总和,并从尝试中获取最大分数并根据分数对其进行排序。我需要最终结果作为排行榜。
$usersByScore = Attempt::where('game_id',$id)
->select('user_id','attempt_no','game_id',DB::raw('SUM(score) as total_score'))
->groupBy('attempt_no')
->orderBy('total_score', 'DESC')
->get()
这给了我排行榜,但它有来自用户的所有尝试。我只需要按分数降序排列的每个用户的最大分数尝试。
解决方案
为此使用 distinct() 方法:我希望它会起作用。
$usersByScore = Attempt::where('game_id',$id)
->select('user_id','attempt_no','game_id',DB::raw('SUM(score) as total_score'))
->groupBy('attempt_no')
->orderBy('total_score', 'DESC')
->distict()
->get()
推荐阅读
- java - 如何在android中动态添加入口芯片和图标
- javascript - d3.js 圆环图 - 向突出显示的部分添加阴影
- javascript - Set element to special coordinates even with position relative?
- java - 通过命令行 jdb 运行 java 程序可以正确执行,但在作为 java 命令行执行时会失败
- elastic-stack - 为什么弹性搜索的 curl 命令在 Ubuntu 中不起作用?
- android - 如何在后台模式下使用 RNFirebase 在 React Native 中显示 Heads-Up 通知?
- linux - 如何在 ftrace/trace-cmd 中获取“}”之后的函数名
- kubernetes - 无法将日志发送到 Graylog kubernetes
- sql-server - 为什么 SQL 内连接称为内连接,外连接称为外连接?
- java - 使用 Android 的媒体播放器处理播放声音