mysql分组查询n条记录
当业务逻辑越来越复杂时,这个查询的需求会越来越多,今天写成笔记记录下来,防止再忘记
SELECT * FROM `notice` a where add_time > 1513008000 and admin_id >= 1 and admin_id <= 10 and status = 0 and
3 > (SELECT COUNT(1) FROM `notice` where add_time > 1513008000 and admin_id >= 1 and admin_id <= 10 and status = 0 and admin_id = a.admin_id and add_time > a.add_time )
ORDER BY admin_id
虚拟一个业务,查询通知表,时间大于今天,管理员id在1到10之间,通知状态为0,重点是根据管理员分组,取每个分组的时间最大的3条
注:主查询和子查询的其他条件需保持一致,子查询的分组依据字段(admin_id)需相等,再根据排序依据字段(add_time)做大于判断