我想运行以下查询以循环插入表中:
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/