工作中遇到的問題,先記錄一下,方便以后查看
存在兩張表,user表和friend表
user表部分字段,如上圖
friend表部分字段,如上圖
往friend表插入千條數據,friend表中的userId值是固定的,對應的friendId是從user表中獲取
實現方案:
1、游標存儲:
-- 在windows系統中寫存儲過程時,如果需要使用declare聲明變量,需要添加這個關鍵字,否則會報錯。 delimiter // drop procedure if exists insertUserFriend; CREATE PROCEDURE insertUserFriend(id int, idx int, size int) BEGIN -- 創建接收游標數據的變量 declare c int; -- 創建結束標志變量 declare done int default FALSE; -- 創建游標 declare cur cursor for select userId from u_user where userId != id LIMIT idx, size; -- 指定游標循環結束時的返回值 declare continue HANDLER for not found set done = TRUE; -- 打開游標 open cur; -- 開始循環游標里的數據 read_loop:loop -- 根據游標當前指向的一條數據 fetch cur into c; -- 判斷游標的循環是否結束 if done then leave read_loop; -- 跳出游標循環 end if; INSERT INTO u_user_friend (userId, friendId, createTime, lastExchangeTime) VALUES (id, c, NOW(), NOW()); -- 結束游標循環 end loop; -- 關閉游標 close cur; -- 輸出結果 select * from u_user_friend WHERE userId = id; END; // -- 調用位置修改值就可以,不用重建存儲過程 CALL insertUserFriend(7071, 0, 5082);
2、while循環---待測試
DELIMITER;// create procedure myproc() begin declare num int; declare num1 int; DECLARE oldUserId int; DECLARE newUserId int; DECLARE isExist int;-- 用於驗證是否存在好友關系 set num=1; set num1=1; set oldUserId=0; set newUserId=0; set isExist=0; while num <= 100 do select min(userId) into oldUserId from u_user where userId>oldUserId; set num1=1; while num1 <= 1000 do set newUserId=newUserId+1; select min(userId) into newUserId from u_user where userId>newUserId; if (newUserId>0 and oldUserId>0) THEN select count(userId) into isExist from u_user_friend where (userId=oldUserId and friendId=newUserId) or (userId=newUserId and friendId=oldUserId); if(isExist=0) THEN INSERT INTO `u_user_friend` (`userId`, `friendId`, `memo`, `des`, `img`, `mps`, `black`, `createTime`, `blackTime`, `lastExchangeTime`) VALUES (oldUserId, newUserId, NULL, NULL, NULL, NULL, b'0', NOW(), NOW(), NOW()); END IF; END IF; set num1=num1+1; set isExist=0; end while; set oldUserId=oldUserId+1; set num=num+1; end while; commit; end;// -- 執行存儲過程 CALL myproc(); -- 刪除存儲過程 -- drop PROCEDURE myproc -- 清空u_user_friend里面的所有數據(慎用) -- truncate table u_user_friend
附:
delimiter的作用:告訴解釋器,這段命令是否已經結束了,mysql是否可以執行了
默認情況下,delimiter是‘;’但是當我們編寫procedure時,如果是默認設置,那么一遇到‘;’,mysql就要執行,這是我們不希望看到的