在错误插入中保留顺序主键
我在mysql中的创建表命令是
CREATE TABLE `map` (
`id` int(4) AUTO_INCREMENT NOT NULL,
`city` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = InnoDB;
CREATE UNIQUE INDEX `map_city_idx`
ON `map`
(`city`);
初始值,例如:
id(1),city('Banda Aceh')
id(2),city('Medan')
下一个插入是city('Medan'),所以这是错误的,因为city列是唯一的。接下来插入的是city('Bengkulu'),最终表结果不是
id(1), city('Banda Aceh')
id(2), city('Medan')
id(4), city('Bengkulu')
id(3)而是id(4)。那么,即使之前存在插入错误,我怎样才能保持顺序主键呢?
id(1), city('Banda Aceh')
id(2), city('Medan')
id(3), city('Bengkulu')
My create table command in mysql is
CREATE TABLE `map` (
`id` int(4) AUTO_INCREMENT NOT NULL,
`city` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = InnoDB;
CREATE UNIQUE INDEX `map_city_idx`
ON `map`
(`city`);
Intial value, like:
id(1),city('Banda Aceh')
id(2),city('Medan')
The next insert is city('Medan'), so it's error because city column is unique. The next insert is city('Bengkulu'), and the final table result is
id(1), city('Banda Aceh')
id(2), city('Medan')
id(4), city('Bengkulu')
It's not id(3) but id(4) instead. So how could I keep sequential primary key eventhough there was/were insert error before?
id(1), city('Banda Aceh')
id(2), city('Medan')
id(3), city('Bengkulu')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这看起来像 InnoDB 的行为。 InnoDB回滚事务,但自增键无法恢复,因为它可能被其他人使用。这在 MyISAM 表中不会发生,但使用 InnoDB,您可以使用事务来防止这种情况发生。我将用 php 编写此内容,但您可以用您想要的任何语言重复它:
That looks like InnoDB behaviour. InnoDB rolls back the transaction, but autoincrement key can not be restored because it might be used by someone else. This doesn't happen in MyISAM tables, but with InnoDB you have the power to prevent it using transactions. I'll write this in php, but you can repeat it in any language you want: