我正忙于将旧网站转移到新主机。 现在差不多完成了,但是数据库出了点问题,一些主键没有变成 AUTO_INCREMENT。所以现在我有很多重复的 ID 都是 0。
在 SQL 中有没有一种方法可以将所有 id 的 where = 0 更新为加上那些? 最后一个填充好的 ID 是“2108”,所以下一个 ID 需要是“2109”,然后是++ 它们。
SELECT * FROM `x9i8Z_yoast_seo_links` WHERE `id` = 0
请帮帮我
最佳答案
MySQL 8.0.2 之前的解决方案将使用 User-defined variables .由于在您的情况下排序并不重要,我们可以直接确定连续的行号值(无需担心顺序)。它将从“最后一个好 ID”值 + 1 开始。然后我们将更新行的 id
值,其中 id
值为 0。
UPDATE `x9i8Z_yoast_seo_links` AS t
CROSS JOIN (SELECT @rn := 2108) AS user_init -- 2108 is your "last good id"
SET t.id = (@rn := @rn + 1)
WHERE t.id = 0
演示 - 架构 (MySQL v5.7)
create table test
(id int);
insert into test
values (1),(2),(3),(4),(0),(0),(0),(0);
查询#1:更新操作前的数据
select * from test;
| id |
| --- |
| 1 |
| 2 |
| 3 |
| 4 |
| 0 |
| 0 |
| 0 |
| 0 |
查询#2:更新操作完成
update test AS t
cross join (select @rn := 4) AS user_init
set t.id = (@rn := @rn + 1)
where t.id = 0;
查询 #3:更新操作完成后的数据
select * from test;
| id |
| --- |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
关于MySQL 重复 'ID' = 0 并且无法将 AUTO_INCREMENT 放在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53297474/