在 MySQL 中插入序列号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8862215/
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 22:22:37  来源:igfitidea点击:

Insert sequential number in MySQL

mysqlsql

提问by Rendicahya

I added an empty column to a table and now I want to insert sequential numbers to its rows. Is it possible to do it using SQL?

我在表中添加了一个空列,现在我想在其行中插入序列号。是否可以使用 SQL 来做到这一点?

回答by dfsq

Run the following queries to have incremented value in yourFieldcolumn:

运行以下查询以增加yourField列中的值:

SELECT @i:=0;
UPDATE yourTable SET yourField = @i:=@i+1;

回答by Jahan

As I said in comments you can update every row with it's row number,

正如我在评论中所说,你可以用它的行号更新每一行,

Here is a linkto how to calculate rownum it mysql.

这是如何计算 mysql 的 rownum的链接

To rephrase:

改写:

update player,
       (select @rownum:=@rownum+1 ‘rank', p.* 
        from player p,
        (SELECT @rownum:=0) r 
        order by score desc) player1
 set thatColumn= rank
 where player.id = player1.id

回答by PresleyDias

try this auto incrementif you wanted to have incremental number in your table for each insert that you do

如果您想在表中为您执行的每个插入操作增加编号,请尝试此自动增量

create table WithAutoInc(somID int AUTO_INCREMENT,somName_ char(100) ,primary key(somID ));

now to insert you can do this

现在插入你可以这样做

 insert into WithAutoInc (somName_) values ('presley');

the result is

结果是

enter image description here

在此处输入图片说明