为一组执行此操作很简单:
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
现在让我们假设有一个groups
包含数千个组 ID 的表。如何为纯 MySQL 中的每个组 ID 执行此插入?
为一组执行此操作很简单:
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
现在让我们假设有一个groups
包含数千个组 ID 的表。如何为纯 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();