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

标签 php mysql laravel

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

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

相关文章:

php - 使用 laravel eloquent 在 MySQL 中搜索波斯字符串

php - Laravel 中的 psr-4 自动加载问题

php - 多维 PHP 数组到 JSON 数组

c# - 错误 "check the manual that corresponds to your MySQL server version"

php - 如何使用 WooCommerce 成员(member) Hook

MYSQL 查找表中的空字段

mysql - 如何设计存储表快照的关系型数据库?

php - Laravel JWT - 使用 Javascript 使用你自己的 API

php - 如何从一个输入框写入多个外国字段?

php - 防止返回按钮显示 POST 确认警报