我的程序有问题
。我有表 oferty_in
其中包含字段(id、status、...、id_om)。我想要检查具有相同 id_om
的是否存在
行的程序。
如果存在,则删除状态 = 'N' 的行(N - 新)。
我的程序几乎可以工作,但我在循环迭代时遇到问题。每次我运行程序时,程序都会删除一半行。我不知道问题出在哪里...
DELIMITER //
CREATE PROCEDURE check_duplicates_oferty_in()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE v_id_del BIGINT;
SELECT count(*) INTO n FROM oferty_in where status_oferty = 'N';
SET i=0;
WHILE i<n DO
IF EXISTS (SELECT id_om FROM oferty_in group by id_om having count(*) >= 2 LIMIT i,1) THEN
SELECT id_om INTO v_id_del FROM oferty_in group by id_om having count(*) >= 2 LIMIT i,1;
DELETE from oferty_in where id_om = v_id_del and status_oferty = 'N';
END IF;
SET i=i+1;
END WHILE;
END
//
我也尝试:
IF EXISTS (SELECT id_om FROM oferty_in group by id_om having count(*) >= 2 LIMIT i,1) THEN
SELECT id_om INTO v_id_del FROM oferty_in group by id_om having count(*) >= 2 LIMIT i,1;
DELETE from oferty_in where id_om = v_id_del and status_oferty = 'N';
SET i=i+1;
ELSE
SET i=i+1;
END IF;
但是都是一样的。
每次都是半行。当 status = 'N'
时,我使用计数器“i”和 while 循环
在 oferty_in
中的行上逐行迭代。有人知道我做错了什么吗?感谢您的帮助和时间。
最佳答案
当 id_om
重复时,您似乎想要删除 status
= 'N' 的行。
I want procedure which check if exist rows with the same id_om. If exist, delete rows where status = 'N' (N - new).
非工作代码通常无助于解释逻辑,所以这就是我要做的。
您绝对不需要为此使用循环结构,也不需要游标:
delete o
from oferty_in o join
(select o2.id_om
from oferty_in o2
group by o2.id_om
having count(*) > 1 and sum(status = 'N') > 0
) o2
on o.id_om = o2.id_om
where o.status = 'N';
关于mysql - 增量变量和存储过程检查重复项的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54289771/