【mysql】批量插入数据(插入数据部分来之其他表)

要求:对A表进行批量数据插入,部分字段值来源于其他表字段

(1)代码:

delimiter $$     
create procedure preG()		
begin
declare i int;		
set i=6001;
while i<9000 do		
	-- 关键词 'IGNORE'
	insert IGNORE into assisted_subscribe_detail (id,catalog_id,material_id,unit_id,semester_id,grade_id,user_id,datecreated,studentnum,teachnum,type,subscribe_id)
	select i,ml.id, ml.material_id,1, ml.semester_id,jc.grade_id,2,now(),567,45,'subscribe',8 from assisted_catalog ml 
	inner join assisted_material jc on jc.id = ml.material_id;
	set i=i+1;		
end while;
end 
$$		

call preG();		

这种方法插入的数据是重复的,即从其他表获取的字段都是重复的第一条记录。

(2)代码:

delimiter $$
CREATE PROCEDURE insertPresaleO()
BEGIN
	-- 这四条数据是需要从另外两张表字段中获取
	declare catalogId bigint(20);		-- 所属征订目录
    declare materialId bigint(20);		-- 所属教材
	declare semesterId bigint(20);		-- 所属学期
    declare gradeId	bigint(20);			-- 所属年级
    
    declare done int default 0;			-- 用于判断是否结束循环
    declare flag int default 0;			-- 标记数据库是否包含此条记录
    
    -- 定义游标,并将需要获取德字段存储到结果集
    declare idCur cursor for select ml.id, ml.material_id, ml.semester_id,jc.grade_id 
    from assisted_catalog ml 
	inner join assisted_material jc on jc.id = ml.material_id;
    declare continue handler for not found set done =1;
    open idCur;
    -- 开始循环
    repeat
    -- 通过游标获取的结果集
    fetch idCur into catalogId,materialId,semesterId,gradeId;
    if not done then
		-- 判断插入的表中是否有重复字段,有则删除该条记录,没有则执行插入语句
		select count(*) into flag from assisted_subscribe_detail zd where zd.catalog_id=catalogId;
		if(flag>0) then
        delete from assisted_subscribe_detail where catalog_id=catalogId;
        end if;
		-- 需要从其他表获取的数据使用结果集标识的字段;直接使用原表字段的话,添加的都是其他表的第一条记录的重复数据
         insert IGNORE into assisted_subscribe_detail (id,catalog_id,material_id,unit_id,semester_id,grade_id,user_id,datecreated,studentnum,teachnum,type,subscribe_id)
			select (select max(id)+1 from assisted_subscribe_detail ),catalogId,materialId,1,semesterId,gradeId,2,now(),567,45,'retreating',8
            from assisted_catalog ml 
			inner join assisted_material jc on jc.id = ml.material_id where jc.id = ml.material_id;
	end if;
	until done end repeat;
	close idCur; 	-- 关闭游标
end
$$
call insertPresaleO();	-- 调用存储方法

DROP PROCEDURE  insertPresaleO	-- 关闭存储方法
这个是通过游标方法逐步实现去重复插入数据;

猜你喜欢

转载自blog.csdn.net/qq_30805957/article/details/80897676