我有一个类似如下的表条目:
+---------+---------+----------+
| Test_id | User_id | Attempts |
+---------+---------+----------+
| 12 | 5 | 1 |
| 13 | 5 | 1 |
| 12 | 5 | 2 |
+---------+---------+----------+
现在我想选择按 test_id
分组的元素,应该得到最新的条目。
我试过这个查询:
$tests_took = Testresult::where('course_id', $courseId)
->where('user_id', Auth::id())
->groupby('test_id')
->orderBy('attempts', 'desc')
->get();
当我显示结果时,我只得到前两行(一个 test_id 只得到一行——这是我想要的。)但是对于 test_id=12,它显示的不是最后一行,而是第一行.我总是希望展示最大的尝试。
我当前的输出是这样的:
| 12 | 5 | 1 |
| 13 | 5 | 1 |
但我想要这个:
| 12 | 5 | 2 |
| 13 | 5 | 1 |
我怎样才能做到这一点?在我使用 groupby 时获取最新行作为第一个数组元素,还是有其他方法可以做到这一点?
最佳答案
ORDER BY
和 GROUP BY
不能很好地协同工作...
如果您只是想要每个 test_id 的最高尝试次数,我建议使用 MAX()
函数:
$tests_took = Testresult::select('test_id', 'user_id', DB::raw('MAX(attempts) AS max_attempts'))
->where('course_id', $courseId)
->where('user_id', Auth::id())
->groupby('test_id')
->get();
关于php - 在 Laravel 中使用 groupby 选择最新的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29170068/