简体   繁体   English

SQL-尝试在现有表中插入新列,其中值从50开始自动递增1

[英]SQL - Trying to insert a new column in an existing table where the values are auto incremented by 1 starting from 50

 ALTER TABLE advance_d ADD testcolumn INTEGER NOT NULL AUTO_INCREMENT;

This is the sql code i typed. 这是我输入的sql代码。 i have a table called advace_d. 我有一个名为advace_d的表。 It has a primary key column called "ad_id" . 它具有一个名为“ ad_id”的主键列。 when i wrote this code ALTER TABLE advance_d ADD testcolumn INTEGER; 当我编写此代码ALTER TABLE advance_d ADD testcolumn INTEGER; a new column was created with null values. 使用空值创建了一个新列。 I want to know how to create the column with values starting from a given value auto incremented by 1. 我想知道如何创建从给定值开始自动增加1的值的列。

so my table would have 1 primary key column for ID and another column with values starting from 50 incremented by 1. 因此我的表将有1个ID的主键列和另一个值从50开始加1的列。

The only way I know how to do this is via insertion into a table with an auto increment column. 我知道如何执行此操作的唯一方法是通过插入具有自动增量列的表中。 I don't know how to do this with your existing table, but you can create a new one, and then copy the previous table over to it, populating the auto increment column in the process: 我不知道如何使用现有表执行此操作,但是您可以创建一个新表,然后将上一个表复制到该表上,并在此过程中填充自动增量列:

CREATE TABLE newTable (col1, col2, ..., colAuto INT NOT NULL AUTO_INCREMENT);
INSERT INTO newTable (col1, col2, ..., colAuto)
SELECT col1, col2, ..., NULL   -- NULL for colAuto
FROM yourTable
ORDER BY ad_id;

This should result in a new table with the same data, and a column colAuto which starts as 1, as ordered by the ad_id column in your original table. 这将导致具有相同数据的新表,以及以原始表中ad_id列的顺序从1开始的colAuto列。 After this, you may alter colAuto if you don't want it to be auto increment anymore. 此后,如果您不希望colAuto成为自动增量,则可以更改colAuto You may also delete the original table if it no longer serves any purpose. 如果原始表不再具有任何用途,您也可以删除它。

Edit: 编辑:

We might also be able to do this using a row number session variable: 我们也可以使用行号会话变量来做到这一点:

SET @rn := 0;
UPDATE yourTable
SET colAuto = (SELECT @rn := @rn + 1 )
ORDER BY ad_id;

But in practice, doing such an update into a non auto increment column may not make much business sense. 但是实际上,对非自动增量列进行这种更新可能没有多大商业意义。 This is because as soon as you add more data to your table, you would have to manually update again, but this time the sequence would be starting from some number other than zero. 这是因为一旦将更多数据添加到表中,就必须再次手动更新,但是这次序列将从零以外的某个数字开始。 Really, an auto increment column is the way to go for easily maintaining a sequence in SQL. 实际上,自动递增列是轻松维护SQL中的序列的一种方法。

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

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