mysql相同的记录显示3条_MySQL去相同记录,但相同记录最多保留三行

用存储过程实现把,容易点:

按照你的表结构,我自己建了两个表:

create table aa (titil varchar(10),pro varchar(10));

p1,usr1

p2,usr1

p3,usr1

p4,usr1

p5,usr1

p1,usr2

p2,usr2

p3,usr2

p4,usr2

p5,usr2

p1,usr3

p2,usr3

p3,usr3

p4,usr3

p5,usr3

p1,usr4

p2,usr4

存储过程如下:

drop procedure test;

delimiter $$

create procedure test()

begin

declare pro_tmp varchar(10);

declare done int;

declare count int;

declare test_cursor cursor for select pro from aa group by pro;

set done=1;

select count(distinct pro) into count from aa;

set @execute_sql='';

open test_cursor;

while done<=count do

fetch test_cursor into pro_tmp;

set @execute_sql =concat(@execute_sql,' (select * from aa where pro=\'',pro_tmp,'\' limit 3 ) union all ');

set done=done+1;

end while;

close test_cursor;

set @execute_sql=left(@execute_sql,length(@execute_sql)-length('union all ')-1);

select @execute_sql;

prepare stmt from @execute_sql;

execute stmt;

end;

$$

delimiter ;

--------------------------------------------

我这边没有根据时间来取,假设你的时间字段是 time ,取最新的三条,需要你改一下存储过程,就是

set @execute_sql =concat(@execute_sql,' (select * from aa where pro=\'',pro_tmp,'\' limit 3 ) union all ');改成

set @execute_sql =concat(@execute_sql,' (select * from aa where pro=\'',pro_tmp,'\' order by time desc limit 3 ) union all ');

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值