Mysql 在有序选择中选择前3行

Mysql 在有序选择中选择前3行,mysql,sql-order-by,limit,greatest-n-per-group,Mysql,Sql Order By,Limit,Greatest N Per Group,我有如下表格数据: id,time,otherdata a,1,fsdfas a,2,fasdfag a,3,fasdfas a,7,asfdsaf b,8,fasdf a,8,asdfasd a,9,afsadfa b,10,fasdf ... 因此,基本上,我可以按照我想要的顺序选择所有数据,方法如下: select * from mytable ordered by id,time; 所以我按照我想要的顺序获取所有记录,首先按id排序,然后按时间排序。但是我需要每个id的最新3次,而不

我有如下表格数据:

id,time,otherdata
a,1,fsdfas
a,2,fasdfag
a,3,fasdfas
a,7,asfdsaf
b,8,fasdf
a,8,asdfasd
a,9,afsadfa
b,10,fasdf
...
因此,基本上,我可以按照我想要的顺序选择所有数据,方法如下:

select * from mytable ordered by id,time;
所以我按照我想要的顺序获取所有记录,首先按id排序,然后按时间排序。但是我需要每个id的最新3次,而不是获取所有记录

答复:

我知道怎么做了。我对它的速度感到惊讶,因为我正在处理数百万行数据,大约需要11秒。我用sql脚本编写了一个过程来完成它,下面是它的样子-请注意,它不是获取最后3行,而是获取最后n行数据

use my_database;

drop procedure if exists getLastN;
drop table if exists lastN;

-- Create a procedure that gets the last three records for each id
delimiter //
create procedure getLastN(n int)
begin
  # Declare cursor for data iterations, and variables for storage
  declare idData varchar(32);
  declare done int default 0;
  declare curs cursor for select distinct id from my_table;
  declare continue handler for not found set done = 1;
  open curs;

  # Create a temporary table to contain our results
  create temporary table lastN like my_table;

  # Iterate through each id
  DATA_LOOP: loop

  if done then leave DATA_LOOP; end if;
  fetch curs into idData;
  insert into lastThree select * from my_table where id = idData order by time desc limit n;

  end loop;
end//

delimiter ;
call getLastN(3);
select * from lastN;

很抱歉,如果这不完全有效,我不得不更改变量名和其他东西来混淆我的工作,但我运行了这段代码,得到了我需要的

我认为这很简单:

SELECT * FROM `mytable`
GROUP BY `id`
ORDER BY `time` DESC
LIMIT 3

我认为这很简单:

SELECT * FROM `mytable`
GROUP BY `id`
ORDER BY `time` DESC
LIMIT 3
试试这个:

select *
from mytable as m1
where (
   select count(*) from mytable as m2
   where m1.id = m2.id
) <= 3 ORDER BY id, time
试试这个:

select *
from mytable as m1
where (
   select count(*) from mytable as m2
   where m1.id = m2.id
) <= 3 ORDER BY id, time

我知道的两种方法是1使用一组并集,每个并集包含一个限制3,或2使用一个临时变量。这些方法以及其他有用的链接和讨论都可以找到。

我知道的两种方法是1使用一组并集,每个并集包含一个限制3,或2使用一个临时变量。可以找到这些方法以及其他有用的链接和讨论。

啊,我明白了。人们总是想要这样奇怪的东西:啊,我明白了。人们总是想要这样奇怪的东西:Pit是一个开始……但这个查询不太管用。我会接受这个想法,看看我是否能让它工作。这是一个开始…但这个查询不太管用。我会接受这个想法,看看能否让它发挥作用。