帮助需要sql查询,选择每个类别的最新5个列表 [英] help need for sql query, select latest 5 lists of each category

查看:37
本文介绍了帮助需要sql查询,选择每个类别的最新5个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MySQL,我有一个包含项目和 5 个类别的数据库表(还有一个 ID 字段,autoincr,PK)我必须选择每个类别的最新 5 个项目,当我使用 group by 时它返回最新的一个项目每个类别,如何在单个查询中获得每个类别的前 5 个项目?

I am using MySQL, I have a database table with items and 5 categories(also one ID field, autoincr,PK) I have to select latest 5 items of each category, when I use group by it return latest one item of each category, how can I get top 5 items of each category in a single query ?

谢谢

推荐答案

你肯定会讨厌这个......

You properly going to hate this ...

(select * from items where category_id=1 order by add_date desc limit 5)
union
(select * from items where category_id=2 order by add_date desc limit 5)
union
(select * from items where category_id=3 order by add_date desc limit 5)
union
(select * from items where category_id=4 order by add_date desc limit 5)
union
(select * from items where category_id=5 order by add_date desc limit 5);

这篇关于帮助需要sql查询,选择每个类别的最新5个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆