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

时间:2019-01-21 12:14:46

标签: mysql sql variables procedure

我的procedure有问题。我有表oferty_in,其中包含字段(标识,状态,...,标识_om)。我想要用相同的if exist检查id_om行的过程。

如果存在,则删除行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;

但是是一样的。 每次排一半。当while loop时,我使用计数器'i'和oferty_in逐行迭代status = 'N'中的行。有人知道我做错了什么吗?感谢您的帮助和时间。

1 个答案:

答案 0 :(得分:0)

重复status时,您似乎想删除id_om ='N'的行。

  

我想要检查是否存在具有相同id_om的行的过程。如果存在,请删除status ='N'(N-新)的行。

非工作代码通常无法帮助解释逻辑,所以这就是我要经过的事情。

为此,您绝对不需要循环构造,也不需要游标:

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';