为一组做这个很简单:
INSERT INTO top_dancers_by_group
SELECT group_id, dancer_id
FROM dancers
WHERE group_id = 1
ORDER BY how_good_they_do_a_half_turn DESC
LIMIT 1000
现在假设有一个包含数千个组 ID 的 groups
表。我如何在纯 MySQL 中为每个组 ID 执行此插入?
最佳答案
我会使用存储过程:
delimiter $$
create procedure insert_top_dancers_by_group()
begin
declare gId int;
declare done tinyint default 0;
declare curGroup cursor for
select distinct group_id from dancers;
declare continue handler for not found
set done = 1;
open curGroup;
group_insert: while done=0 do
fetch curGroup into gId;
if done = 0 then
-- If you want to remove the previous stored dancers for this group:
delete from top_dancers_by_group where group_id = gId;
-- Insert the top dancers for this group:
insert into top_dancers_by_group
select group_id, dancer_id
from dancers
where group_id = gId
order by how_good_they_do_a_half_turn DESC
limit 1000;
end if;
end while;
close curGroup;
end $$
delimiter ;
希望这对您有所帮助。
您还可以在此过程中使用参数来定义插入的行数:
delimiter $$
create procedure insert_top_n_dancers_by_group(n int)
begin
declare gId int;
declare done tinyint default 0;
declare curGroup cursor for
select distinct group_id from dancers;
declare continue handler for not found
set done = 1;
open curGroup;
group_insert: while done=0 do
fetch curGroup into gId;
if done = 0 then
-- If you want to remove the previous stored dancers for this group:
delete from top_dancers_by_group where group_id = gId;
-- Insert the top dancers for this group:
insert into top_dancers_by_group
select group_id, dancer_id
from dancers
where group_id = gId
order by how_good_they_do_a_half_turn DESC
limit n;
end if;
end while;
close curGroup;
end $$
delimiter ;
创建过程后,您可以这样调用它们:
call insert_top_dancers_by_group();
关于MySQL:将每组中的前 N 行插入到表中。假设有数百万组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18520941/