1. 程式人生 > >用儲存過程刪除重複資料且留下一條資料

用儲存過程刪除重複資料且留下一條資料

本來打算用一條sql直接執行,但是資料量太大,所以正好拿儲存過程練練。感謝我的同事對我的幫助。

要求:刪除相同order_id的其他多餘資料。id是主鍵

思路:對資料根據order_id排序,這樣相同資料就會緊挨著,然後使用遊標,也就是迴圈,對比上下兩條記錄的order_id 如相同,刪掉,如不相同,則把此行order_id賦值給一個變數,以便為了下次迴圈的時候比較、

話不多說。上程式碼:

drop PROCEDURE if EXISTS tempProcedure; create PROCEDURE tempProcedure() BEGIN DECLARE count int(20); DECLARE ind int(20); DECLARE lastOrderId bigint(11) unsigned; DECLARE currOrderId bigint(11) unsigned; DECLARE deleteId bigint(11); declare cursorForDel cursor for (select id,order_id from eshop_comment_offline ORDER BY order_id); set ind = 0; set count = 0; select count(id) into count from eshop_comment_offline; -- select count from dual;    --列印總條數 open cursorForDel; while ind <= count do        -- mysql有三種迴圈:while,repeat,loop     fetch cursorForDel into deleteId, currOrderId;     if currOrderId=lastOrderId THEN    -- 當前的order_id已經存在過,當前資料行可以被刪除         delete from eshop_comment_offline where id=deleteId;     else          set lastOrderId = currOrderId;     end if; --     select deleteId,lastOrderId -- 輸出當前獲取到的id與order_id     set ind = ind+1; end while; close cursorForDel; END -- select sum(cc) from ( -- select COUNT(0) cc,order_id from eshop_comment_offline GROUP BY order_id HAVING cc>1 -- ) temp;    -- 要刪1138條, 1138不是當前查出的結果,需要做些處理 1897-759=1138 -- select count(0) from eshop_comment_offline begin; call tempProcedure; commit