插入新关系到现有条目的最快方法是什么?

时间:2017-06-07 07:59:45

标签: mysql sql performance

我需要以一对一的关系为每个俱乐部插入finance_entity。 我决定在mysql服务器中运行它,因为单个插入甚至更慢。我怎样才能优化它以更快地运行?有没有办法破解插入选择这样做?

我不能把club_id放在finance_entity上,因为有多个关系指向它。

alter table clubs add column finance_entity_id int unsigned null after id;
DELIMITER !
drop procedure if exists create_entities!
create procedure create_entities()
begin
    create_entities_for_club: loop
        set @club_key = (select id from clubs where finance_entity_id is null limit 1);

        insert into finance_entity (id) value (null);
        update clubs set finance_entity_id = last_insert_id() where id = @club_key;


        if @club_key is null then 
            leave create_entities_for_club;
        end if;
    end loop create_entities_for_club;
end!
call create_entities_for_club()!

DELIMITER ;

alter table clubs change column finance_entity_id finance_entity_id int unsigned not null;
alter table clubs add unique (finance_entity_id);

2 个答案:

答案 0 :(得分:0)

设置临时密钥似乎是最快的方法。

除此之外,在缓冲区中有足够的大小是必不可少的,结果我的测试机只有16M的缓冲区大小。

将这些添加到my.ini或my.cnf

innodb_buffer_pool_size=1024M
innodb_additional_mem_pool_size = 8M
innodb_log_file_size = 256M
innodb_log_buffer_size = 512M

使用它来插入表格,添加和索引到club_id,可能会更快。

alter table finance_entity add column club_id int unsigned null;
insert into finance_entity (club_id) select id from clubs;

update clubs join finance_entity on clubs.id = finance_entity.club_id 
set finance_entity_id = finance_entity.id;

alter table finance_entity drop column club_id;

对于2万个条目,它在1.6秒内运行。

答案 1 :(得分:0)

如果现有表格为1:1,则只需使用相同的PRIMARY KEY,但不要将其称为AUTO_INCREMENT