日期:2014-05-16  浏览次数:20906 次

mysql循环插入数据

需要在数据库中根据product表中的自增id,如果存在则插入对应的数据到pageview表,数据有几万条

drop procedure if exists autoInsert;

create procedure autoInsert()

begin?

declare i int;

declare j int;

set i=1;

while(i<40001) do

if exists(select auto_id from product where auto_id=i ) then

set j=i;

if (select count(game_id) from pageview where game_id=j)=0 ?then

insert into pageview(game_id,week_pv,last_week_pv,month_pv,total_pv,admin_time) values(i,100+i,50+i,500+i,2000+i,now());

end if;

end if;

set i=i+1;

end while;

end

?

(1)其中循环嵌套时,如果直接嵌套发现总是执行不成功,所以加上了set j = i;

(2)执行效率问题,由于数据量巨大,因此需要将表product和表pageview对应的字段都建立索引。

(3)if语句中选择的东西要保证是索引值,这样效率就会提升很多

?

最终插入4W条数据花费时间:

影响的数据栏: 1 ? ? ?//其中1并不是记录数

时间: 10.266ms


?