在 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
Insert sequential number in MySQL
提问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 yourField
column:
运行以下查询以增加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
结果是