我會用一個存儲過程:
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();
@Strawberry什麼'分組'? – Barranka
很好的問題。我必須吸食一些東西 – Strawberry
這個小組是有效地'group_id'這裏 – Dan