增量变量和存储过程检查重复项的问题

Problem with increment variable and stored procedure to check duplicates

我的 procedure 有问题。我有 table oferty_in,其中包含字段(id、status、...、id_om)。我想要使​​用相同 id_om 检查 if exist 行的程序。

如果存在,删除行 where status = '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 loop 逐行迭代 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';