gpt4 book ai didi

php - 在 Laravel 中使用 groupby 选择最新的行

转载 作者:可可西里 更新时间:2023-11-01 08:15:44 41 4
gpt4 key购买 nike

我有一个类似如下的表条目:

+---------+---------+----------+
| 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 BYGROUP 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/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com