自从我记得自己以后,我在LAMP(Linux + Apache + MySQL + PHP)中开发。但现在有一个问题困扰着我多年。我希望你能帮助我找到答案,并指引我走向正确的方向。这是我的挑战:MySQL和INT auto_increment字段
说,我们正在创建一个社区网站,我们允许我们的用户注册。我们存储所有用户看起来那么像这样的MySQL表:
CREATE TABLE `users` (
`uid` int(2) unsigned NOT NULL auto_increment COMMENT 'User ID',
`name` varchar(20) NOT NULL,
`password` varchar(32) NOT NULL COMMENT 'Password is saved as a 32-bytes hash, never in plain text',
`email` varchar(64) NOT NULL,
`created` int(11) unsigned NOT NULL default '0' COMMENT 'Timestamp of registration',
`updated` int(11) unsigned NOT NULL default '0' COMMENT 'Timestamp of profile update, e.g. change of email',
PRIMARY KEY (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
所以,从这个片断,你可以看到,我们有一个独特的自动递增为每个新用户的UID“字段。正如在每一个良好和忠诚的社区网站上,我们需要为用户提供完全删除他们的个人资料的可能性,如果他们想取消他们参与我们的社区。
这是我的问题。假设我们有3个注册用户:Alice(uid = 1),Bob(uid = 2)和Chris(uid = 3)。现在鲍勃想要删除他的个人资料并停止使用我们的社区。如果我们从'用户'表中删除Bob的个人资料,那么他缺少的'uid'将会创建一个永远不会再填充的差距。在我看来,这是对uid的巨大浪费。我在这里看到3个可能的解决方案:
1)将我们表中'uid'字段的容量从SMALLINT(int(2))增加到例如BIGINT(int(8)),并忽略一些uid的将被浪费。
2)引入新字段'is_deleted',它将用于标记已删除的配置文件(但将它们保留在表中而不是删除它们),以便为新注册的用户重新使用它们的uid。表看起来像这样:
CREATE TABLE `users` (
`uid` int(2) unsigned NOT NULL auto_increment COMMENT 'User ID',
`name` varchar(20) NOT NULL,
`password` varchar(32) NOT NULL COMMENT 'Password is saved as a 32-bytes hash, never in plain text',
`email` varchar(64) NOT NULL,
`is_deleted` int(1) unsigned NOT NULL default '0' COMMENT 'If equal to "1" then the profile has been deleted and will be re-used for new registrations',
`created` int(11) unsigned NOT NULL default '0' COMMENT 'Timestamp of registration',
`updated` int(11) unsigned NOT NULL default '0' COMMENT 'Timestamp of profile update, e.g. change of email',
PRIMARY KEY (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
3)写一个脚本来移动所有后面的用户记录,一旦删除了先前的记录。例如。在我们的情况下,当Bob(uid = 2)决定删除他的配置文件时,我们会用Chris的记录替换他的记录(uid = 3),这样Chris的uid变为2并标记(is_deleted ='1')克里斯的旧纪录为新用户空缺。在这种情况下,我们根据注册时间保留uid的时间顺序,以便老用户使用较低的uid。
请告诉我现在哪种方式是正确的方法来处理auto_increment字段中的空白。这只是用户的一个例子,但这种情况经常出现在我的编程经验中。
提前致谢!
可能的重复[何时修复MYSQL中的自动递增间隔](http://stackoverflow.com/questions/1949842/when-to-fix-auto-increment-gaps-in-mysql) – 2010-05-26 07:16:06