mik*_*ney 0 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
...
Run Code Online (Sandbox Code Playgroud)
所以本质上,我可以通过说以下内容按我想要的顺序选择所有数据:
select * from mytable ordered by id,time;
Run Code Online (Sandbox Code Playgroud)
所以我按照我想要的顺序获取所有记录,首先按 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;
Run Code Online (Sandbox Code Playgroud)
抱歉,如果这不完全有效,我不得不更改变量名称和内容以混淆我的工作,但我运行了这段代码并得到了我需要的东西!
我认为这很简单:
SELECT * FROM `mytable`
GROUP BY `id`
ORDER BY `time` DESC
LIMIT 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23684 次 |
| 最近记录: |