mysql 查询表中不同状态的最新5条记录

本文介绍了一种使用SQL查询优化的方法,通过联合子查询的方式,针对表'status'的四种状态进行高效的数据检索。该方法利用变量计数和降序排列,确保了每个状态的前五条最新记录被准确获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建表:status有4种状态,分别为1,2,3,4

CREATE TABLE `table_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `createtime` datetime DEFAULT NULL,
  `status` tinyint(4) DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='表信息';

 

select @r1:=@r1+1 rn, t.* from (
select ti.id, ti.status, ti.createtime from table_info ti
where ti.status= 1 order by ti.createtime desc) t,(select @r1:=0) tn where @r1 < 5
union all
select @r2:=@r2+1 rn, t.* from (
select ti.id, ti.status, ti.createtime from table_info ti
where ti.status= 2 order by ti.createtime desc) t,(select @r2:=0) tn where @r2 < 5
union all
select @r3:=@r3+1 rn, t.* from (
select ti.id, ti.status, ti.createtime from table_info ti
where ti.status= 3 order by ti.createtime desc) t,(select @r3:=0) tn where @r3 < 5
union all
select @r4:=@r4+1 rn, t.* from (
select ti.id, ti.status, ti.createtime from table_info ti
where ti.status= 4 order by ti.createtime desc) t,(select @r4:=0) tn where @r4 < 5

查询结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值