MySQL中的自动增量 [英] autoincrement in MySQL

查看:443
本文介绍了MySQL中的自动增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表中有一个主键列要自动递增.但是,当我从表中删除具有最高主键ID的行时(让我们说11).然后,下一次我进行插入操作时,它将键插入为12而不是11(尽管在逻辑上它可以使用11,因为没有与键11关联的条目).我该如何做到这一点?

I have one of my primary key column in my table to auto-increment. However when I delete a row from the table that has the highest primary key id (lets say 11). Then the next time I do an insertion it inserts the key as 12 not 11 (though logically it can use 11 as there is no entry associated with the key 11). How can I make this happen?

推荐答案

您确定要这样做吗?一个自动增量列将保证一个唯一的数字,这就足够了.我猜您可以更新下一个自动增量值(我将不得不查询它的工作原理),但是我认为您不应该这样.

Are you really sure you want this? An autoincrement column will guarantee a unique number, and that's enough. You could update the next autoincrement value I guess (i'll have to look it up how that works), but I don't think you should want that.

如果您需要控制一列中的数字,则应该手动进行.

If you need to control the numbers in a column, you should do so manually.

不过,您可以这样更改自动递增编号:

nevertheless, you can change the autoincrement number like so:

ALTER TABLE tbl AUTO_INCREMENT = 100;

(来自: http://dev.mysql .com/doc/refman/5.0/en/example-auto-increment.html )

另一句话:如果您有1到10的数字,并且删除了5,那么您将很难做到这一点.您几乎不能使下一个auto_increment 5变大,因为6已经存在. 再说一次,尽管您可以 为您的示例做一些肮脏的事情,但在实际环境中确实很难做到这一点.也许从描述您的情况开始一个新的问题,并寻求建议,以解决没有auto_increment技巧的问题:)

Another remark: If you have numbers one to ten, and you remove 5, you cannot easily do this. You can hardly make the next auto_increment 5 because 6 is already there. So again, while you can do something dirty for your example, it's really hard to do this in a real environment. Maybe start a new question with description of your situation, and ask for advice how to approach that problem without the auto_increment tricks :)

这篇关于MySQL中的自动增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆