MySQL:将每组中的前 N ​​行插入到表中。假设有数百万组

标签 mysql greatest-n-per-group

为一组做这个很简单:

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/

相关文章:

sql - 在 PostgreSQL 中有效地合并最近日期的两个数据集

sql - 读取连接中的最新值而不执行嵌套 SELECT

Mysql表记录显示歪了

mysql - SQL 查询从有交集的两个表中选择最大值,除非不为空

sql - FirebirdSQL Unique & Max(或 MaxValue)

PHP - 单击按钮时使用 for 循环将 Form Div 递增 1

sql - DISTINCT ON,但获取第二行,而不是第一行

php - 语法错误或访问冲突 : 1064

mysql - SQL-如何将两个表与具有不同条件的两个表计数组合起来

MySQL 查询返回当前日期的 -7 到 +7?