查询中的 MySQL 循环变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23637041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 20:30:53  来源:igfitidea点击:

MySQL Loop Variable in a Query

mysqlsqlloops

提问by Neron

I want to use the loop index "i" in the result of my select statement in order to insert it into another table. Is is like:

我想在我的 select 语句的结果中使用循环索引“i”,以便将其插入到另一个表中。是这样的:

set i=0;
while i<25 do

    insert into a (x,y,z)
    select a,b,i
    from table1;

    set i= i+1;
end while;

What is the way to do it?

有什么方法可以做到?

采纳答案by Neron

DOne :)

完毕 :)

I have just created variable i as @i and it is all solved.

我刚刚创建了变量 i 作为@i,一切都解决了。

Like this:

像这样:

set @i=0;
while @i<25 do

    insert into a (x,y,z)
    select a,b,@i
    from table1;

    set @i= @i+1;
end while;

thx anyway :)

无论如何,谢谢:)

回答by tgkprog

Open the table separately asa cursor, put fields in to variables, then use those variables and i to insert data in to the table with a

作为游标单独打开表,将字段放入变量中,然后使用这些变量和 i 将数据插入表中

insert into a (x,y,z) values (var1, var2, i).

What you have written would put multiple rows in to a table a with each value of i.

您所写的内容会将多行放入表 a 中,每个值都为 i。