Laravel 分组获取数据后 每个分组获取 2 条最新的数据
需求:
每个分组的分类 获取2条最新的数据
数据库:
id title body bind_category_id created_at
1 标题1 内容1 1 2019年11月18日13:45:56
2 标题2 内容2 1 2019年11月18日13:45:57
3 标题3 内容3 2 2019年11月18日13:45:58
4 标题4 内容4 3 2019年11月18日13:45:59
5 标题5 内容5 3 2019年11月18日13:45:60
6 标题6 内容6 3 2019年11月18日13:45:61
实现后 获取到的数据 (也就是根据bind_category_id 分组后,每组去除 最新更新的数据)
id title body bind_category_id created_at
1 标题1 内容1 1 2019年11月18日13:45:56
2 标题2 内容2 1 2019年11月18日13:45:57
3 标题3 内容3 2 2019年11月18日13:45:58
5 标题5 内容5 3 2019年11月18日13:45:60
6 标题6 内容6 3 2019年11月18日13:45:61
:joy: 感觉自己的mysql 好薄弱
请了解一下 Mysql 的
having
关键字select
from table a
where 2>(select count() from table where bind_category_id=a.bind_category_idand created_at>a.created_at)
order by a.bind_category_idand ,a.created_at desc
你可以看一下这个博客,可能会对你有所帮助。
https://n3xtchen.github.io/n3xtchen/postgr...
大概是这样,你要按照自己的改一下。
SELECT from test where id not in(select MAX(id) from test GROUP BY bind_category_id HAVING count() >1)
@青风百里 这个方法是错误的。