admin

MySQL中的WHILE语法错误

sql

我正在尝试在MySQL(5.1.41-3ubuntu12.10-log)数据库的一次性查询中使用while循环:

WHILE ((SELECT COUNT(*) FROM 
    (SELECT id, COUNT(*) AS cnt
        FROM foo
        GROUP BY id
        ORDER BY COUNT(*) DESC) cnts
    WHERE cnt > 1) != 0) DO
BEGIN

SET @curr_id = (SELECT id FROM 
            (SELECT id, COUNT(*) AS cnt
                FROM foo
                GROUP BY id
                ORDER BY COUNT(*) DESC) cnts
            WHERE cnt > 1
            LIMIT 1);


SET @new_id = (SELECT MAX(id) + 1
        FROM foo);

UPDATE foo 
    SET id = @new_id 
    WHERE id = @curr_id 
    LIMIT 1;

END WHILE;

这是 在有多个具有相同ID的记录时,用下一个ID更新其中之一。

主体中的语法是正确的,而while语句中使用的谓词也可以独立执行而没有任何麻烦。MySQL在查询开始时返回语法错误:

Error Code : 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHILE ((SELECT count(*) FROM 
    (SELECT id, COUNT(*) AS cnt
        FROM stock_produ' at line 1

我意识到这可能不是 正确 的做事方式,但是这是一个非常糟糕(或者根本不是全部)的经过深思熟虑的数据库,因此,如果我能以这种方式进行工作,那将是非常棒的。

谢谢,

罗宾


阅读 239

收藏
2021-06-07

共1个答案

admin

似乎您正在尝试将此程序代码作为匿名块运行。尽管这在某些数据库(例如Oracle)中有效,但是在MySQL中却无法完成。

如果要运行此程序,则将其放入存储过程中,然后调用该过程。因此:

建立程序

DELIMITER $$

CREATE PROCEDURE `foo_update_routine`()
BEGIN
  WHILE ((SELECT COUNT(*) FROM 
    (SELECT id, COUNT(*) AS cnt
      FROM foo
      GROUP BY id
      ORDER BY COUNT(*) DESC
    ) cnts
    WHERE cnt > 1) != 0) 
  DO
    SET @curr_id = (SELECT id FROM 
      (SELECT id, COUNT(*) AS cnt
         FROM foo
         GROUP BY id
         ORDER BY COUNT(*) DESC
      ) cnts
      WHERE cnt > 1
      LIMIT 1);

    SET @new_id = (SELECT MAX(id) + 1 FROM foo);

    UPDATE foo SET id = @new_id 
      WHERE id = @curr_id 
      LIMIT 1;

  END WHILE;
END $$

通话程序

CALL `foo_update_routine`;

附注:您可能希望调查select语句的HAVING子句

2021-06-07