我正在尝试更新一些行。我只想更新 ID=0 的行。
我收到的错误消息是:
这是我正在使用的代码。欢迎大家提出意见!
UPDATE ch_15_posts SET ID = (select MAX(ID)+1 as max FROM `ch_15_posts`)
WHERE ID = 0
Run Code Online (Sandbox Code Playgroud)
MySQL 不允许您在 UPDATE 或 DELETE 同一表的同一语句中从表中进行 SELECT。
mysql> UPDATE ch_15_posts SET ID = (select MAX(ID)+1 as max FROM `ch_15_posts`) where id = 0;
ERROR 1093 (HY000): You can't specify target table 'ch_15_posts' for update in FROM clause
Run Code Online (Sandbox Code Playgroud)
有一种解决方法可以执行一种双子查询,它会提前评估内部子查询,并将结果存储在临时表中。然而,这不会得到你想要的,因为它只运行一次子子查询,并且它将生成一个值并将其分配给 id = 0 的所有行。
mysql> UPDATE ch_15_posts SET ID = (select max from (select MAX(ID)+1 as max FROM `ch_15_posts`) t) where id = 0;
Query OK, 3 rows affected (0.02 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Run Code Online (Sandbox Code Playgroud)
看起来您正在尝试将自动递增值分配给无意中设置了值 0 的行。您无法在不锁定表的情况下使用 MAX(id)+1 方法,因为其他并发会话可能会插入新行当你这样做的时候。所以这是一个竞争条件。
但是您可以通过使列成为自动增量键来自动回填自动增量值。
演示:
mysql> create table c_15_posts (id int );
mysql> insert into c_15_posts values (0), (2), (0), (6), (0), (42);
Query OK, 6 rows affected (0.02 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> alter table c_15_posts modify id int auto_increment primary key;
Query OK, 6 rows affected (0.04 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> select * from c_15_posts;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 6 |
| 7 |
| 42 |
+----+
Run Code Online (Sandbox Code Playgroud)
带有 0 的行不是从 43 开始,但它们确实接收唯一值。下一次插入将获得 id 43。
| 归档时间: |
|
| 查看次数: |
7723 次 |
| 最近记录: |