本来打算用一条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