mysql - 错误 1064 : Cannot execute while loop in mysql using variables

标签 mysql while-loop

我想运行以下查询以循环插入表中:

SET @maxid =  ( select max( length( id ) ) from article ) ;
SET @x=1;
WHILE @x<= @maxid DO
 INSERT INTO `article_responder` 
   (article_id, username, reply_id)
   SELECT @x, p.username, p.id
   FROM article AS a, post AS p
   WHERE a.id=@x AND p.article_id=@x ;
 SET  @x = @x + 1; 
 END WHILE;

但我收到此错误:

ERROR 1064 (42000): 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 'END WHILE' at line 

注意,article_id不能自增,因为业务登录要求插入数据后,article_responder的下一行可以是任意文章。所以我不知道如何用通常的连接来填充article_responder

如何修复它?

最佳答案

我建议将 article_id 设为主键自动增量列,然后执行以下 INSERT INTO ... SELECT:

INSERT INTO article_responder (username, reply_id)
SELECT p.username, p.id
FROM post p
INNER JOIN article a
    ON a.id = p.article_id;

请注意,逻辑WHERE a.id=@x AND p.article_id=@x相当于说a.id = p.article_id

关于mysql - 错误 1064 : Cannot execute while loop in mysql using variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56748638/

相关文章:

php - AJAX 调用后 jQuery 未重定向

mysql - 数据库设计——哪一种更好?

c# - 一些 RS 字段保留为零,而其他字段则不是 (ADODB)

javascript - 简单的 while 循环出现问题

mysql - 使用两个 MySQL 循环填充表

sql - 当需要计数器时,避免在 SQL 中使用 while 循环

java - while 循环之外的 ArrayList 未更新

mysql - 对于这个 MySQL 查询有更好的方法吗?

c - 尽管满足条件,循环仍然重复

python - 将参数传递给torndb.query()