2013-08-29 18 views
1

這樣做對一組很簡單:MySQL:將每組的前N行插入表中。假設百萬組

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中爲每個組標識執行此插入操作?

+0

@Strawberry什麼'分組'? – Barranka

+0

很好的問題。我必須吸食一些東西 – Strawberry

+0

這個小組是有效地'group_id'這裏 – Dan

回答

2

我會用一個存儲過程:

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(); 
+0

布拉沃,謝謝。這裏有很多新的MySQL特性供我使用,但我想我理解了所發生的一切。假設組ID是一個字符串,我會'聲明gId varchar(32)'或類似的東西嗎?另外,是否沒有實際的內聯方式來實現這一目標? – Dan

+0

@丹我很高興這對你有用。當然,'gId'必須與表中'group_id'字段的類型相同。而且......我認爲這是最便宜的方法,特別是如果你正在處理一張大桌子。 (如果它是有用的,接受它;-)) – Barranka

+0

謝謝,正在努力實現它現在 – Dan