自從我記得自己以後,我在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