简体   繁体   English

创建表后在mysql中增加值

[英]increment value in mysql after the table has been created

I would like to change the value in the second column to increment and also change the current NULL values to start using that incrementing system that begins at a value other than 1. I do see I can use我想将第二列中的值更改为递增,并更改当前的 NULL 值以开始使用从 1 以外的值开始的递增系统。我确实看到我可以使用

ALTER TABLE t2 AUTO_INCREMENT = value;

to change the table to start incrementing at the number I want it to but the values them selves are still null how do I change my table from this:更改表格以开始以我想要的数字递增,但它们本身的值仍然为空,我该如何更改我的表格:

| Id | OtherNumber | Name |
| -- |:-----------:| ----:|
| 1  | NULL        | Bob  |
| 2  | NULL        | Susan|
| 3  | NULL        | Bill |

to this对此

| Id | OtherNumber | Name |
| -- |:-----------:| ----:|
| 1  | 7           | Bob  |
| 2  | 8           | Susan|
| 3  | 9           | Bill |

How would I make the change if the table is in the hundreds of rows?如果表格有数百行,我将如何进行更改? Thanks谢谢

If you make "OtherNumber" the primary key when you alter it to auto increment, mysql should fill in the values for you如果在将“OtherNumber”更改为自动递增时将其设为主键,mysql 应为您填写值

To change the starting number, it seems you need to use the old primary id column to get the "first" row in the table.要更改起始编号,您似乎需要使用旧的主 ID 列来获取表中的“第一”行。 Mysql will then pick this value to start the auto increment from. Mysql 然后会选择这个值来开始自动增量。

update t2 set OtherNumber = value where t2.Id = 1;
ALTER TABLE `test`.`new_table` 
CHANGE COLUMN `OtherNumber` `OtherNumber` INT(11) NOT NULL AUTO_INCREMENT ,
ADD PRIMARY KEY (`OtherNumber`);

The nulls should be filled in with your auto increment setting.应使用您的自动增量设置填充空值。

You can later change the primary key back to the id column.您可以稍后将主键更改回 id 列。

how about if you leave Id as auto-increment, drop the OtherNumber column, and when you do a select, have OtherNumber be a derived column=Id+6如果您将Id保留为自动增量,如何删除OtherNumber列,并且当您进行选择时,让OtherNumber成为派生列 =Id+6

There, maybe some other Answers will come along.在那里,也许会出现其他一些答案。 Others could be better.其他人可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM