重新计算 SQL 自动递增 ID,同时保持其他列不变

Recount SQL auto increment ID while keeping the other columns intact

我有一个table这样的

ID NAME
1 MICHAEL
2 JORDAN
5 DONALD
7 JAYCE
8 ROY
11 JOHN
16 DOE

有没有办法从头开始重新计算 ID,所以有一个 sequel 并保持其他列完好无损,如下所示:

ID NAME
1 MICHAEL
2 JORDAN
3 DONALD
4 JAYCE
5 ROY
6 JOHN
7 DOE

谢谢!

如果您的 MySQL 版本支持 window 功能,您可以使用 ROW_NUMBER.

假设您有以下 table:

create table test(
ID int NOT NULL ,
NAME VARCHAR (25)
);

insert into test values 
(1,'MICHAEL'),
(2,'JORDAN'),
(5,'DONALD'),
(7,'JAYCE'),
(8,'ROY'),
(11,'JOHN'),
(16,'DOE');

使用 row_number 会得到:

select ID,NAME, row_number() over(order by ID ASC ) as rownum
from test

Result:

ID    NAME    rownum
1   MICHAEL     1
2   JORDAN      2
5   DONALD      3
7   JAYCE       4
8   ROY         5
11  JOHN        6
16  DOE         7

现在,创建另一个 table test2

create table test2(
ID int NOT NULL ,
NAME VARCHAR (25)
);

我们可以使用INSERT INTO SELECT:

INSERT INTO test2( ID, NAME )
  WITH cte AS (
            select ID,NAME, row_number() over(order by ID ASC ) as rownum
            from test t1
  )
  SELECT rownum,NAME
  FROM cte;

select * from test2;

Result:

ID    NAME
1 MICHAEL
2 JORDAN
3 DONALD
4 JAYCE
5 ROY
6 JOHN
7 DOE

fiddle