Php 使用Laravel中的groupby选择最新的行
我有一个类似如下的表格条目:Php 使用Laravel中的groupby选择最新的行,php,mysql,laravel,Php,Mysql,Laravel,我有一个类似如下的表格条目: +---------+---------+----------+ | Test_id | User_id | Attempts | +---------+---------+----------+ | 12 | 5 | 1 | | 13 | 5 | 1 | | 12 | 5 | 2 | +---------+---------+----------+ 现在我
+---------+---------+----------+
| Test_id | User_id | Attempts |
+---------+---------+----------+
| 12 | 5 | 1 |
| 13 | 5 | 1 |
| 12 | 5 | 2 |
+---------+---------+----------+
现在我想通过test\u 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
不能很好地协同工作
如果您只是想获得每个测试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();
您可以使用以下行:
Testresult::select('*')
->join(DB::raw('(Select max(id) as last_id from Testresult group by test_id) LatestId'), function($join) {
$join->on('Testresult.id', '=', 'LatestId.last_id');
})
->orderBy('attempts', 'desc');
}
它仍然显示第一行而不是最后一行。嗯,这很奇怪。尝试
作为最大尝试
而不是作为尝试
。虽然我认为这不会有什么不同,但也许的确如此……这很有帮助。非常感谢:)关于被接受的答案,这是新的吗?