【问题标题】:Problem with increment variable and stored procedure to check duplicates增量变量和存储过程检查重复项的问题
【发布时间】:2019-01-21 12:14:46
【问题描述】:

我的procedure 有问题。我有表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 中的行。有人知道我做错了什么吗?感谢您的帮助和时间。

【问题讨论】:

    标签: mysql sql variables procedure


    【解决方案1】:

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

    我想要检查是否存在具有相同 id_om 的行的过程。如果存在,则删除 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';
    

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      相关资源
      最近更新 更多