我需要在一對一的關係中爲每個俱樂部插入一個finance_entity。 我決定在mysql服務器上運行它,因爲單個插入速度更慢。我怎麼能優化這個跑得更快?有沒有辦法破解插入select來做到這一點?什麼是插入與現有條目的新關係的最快方式?
我不能把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);
也就是說,做一個查詢中的所有行;不要圍繞1行查詢進行循環。 –