用存储过程实现把,容易点:
按照你的表结构,我自己建了两个表:
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 ');