重新整理AUTO_INCREMENT字段
2016-01-21 Netkiller Netkiller
节选择《Netkiller MySQL 手札》
13.9. 重新整理AUTO_INCREMENT字段
AUTO_INCREMENT 并非按照我们意愿,顺序排列,经常会跳过一些数字,例如当插入失败的时候,再次插入会使用新的值。有时会造成浪费,我们可以使用下面SQL重新编排AUTO_INCREMENT序列。
SET @newid=0; UPDATE mytable SET id = (SELECT @newid:=@newid+ 1);
使用max()查看最大值,然后使用 alter修改起始位置。
select max(id) from mytable; ALTER TABLE mytable AUTO_INCREMENT = 1000;
注意外键,需要 ON UPDATE CASCADE 支持,否则无法更新。CONSTRAINT `FK_group_has_contact_contact` FOREIGN KEY (`contact_id`) REFERENCES `contact` (`id`) ON UPDATE CASCADE ON DELETE CASCADE,
CREATE TABLE `contact` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '唯一ID', `name` VARCHAR(50) NOT NULL COMMENT '姓名', `mobile` VARBINARY(32) NULL DEFAULT NULL COMMENT '手机号码', `email` VARBINARY(50) NULL DEFAULT NULL COMMENT '电子邮件', `mobile_digest` VARCHAR(32) NULL DEFAULT NULL COMMENT '摘要', `email_digest` VARCHAR(32) NULL DEFAULT NULL COMMENT '邮件摘要', `birthday` DATE NULL DEFAULT NULL COMMENT '生日', `description` VARCHAR(255) NULL DEFAULT NULL COMMENT '备注描述', `status` ENUM('Subscription','Unsubscribe') NOT NULL DEFAULT 'Subscription' COMMENT '订阅状态', `ctime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `mtime` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间', PRIMARY KEY (`id`), UNIQUE INDEX `digest` (`mobile_digest`, `email_digest`) ) COMMENT='会员手机短信与电子邮件映射表' COLLATE='utf8_general_ci' ENGINE=InnoDB AUTO_INCREMENT=43642; CREATE TABLE `group` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, `description` VARCHAR(512) NOT NULL, `ctime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE INDEX `name` (`name`) ) COMMENT='短信分组' COLLATE='utf8_general_ci' ENGINE=InnoDB AUTO_INCREMENT=8; CREATE TABLE `group_has_contact` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `group_id` INT(10) UNSIGNED NOT NULL, `contact_id` INT(10) UNSIGNED NOT NULL, `ctime` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE INDEX `group_contact` (`group_id`, `contact_id`), INDEX `FK_group_has_contact_contact` (`contact_id`), CONSTRAINT `FK_group_has_contact_contact` FOREIGN KEY (`contact_id`) REFERENCES `contact` (`id`) ON UPDATE CASCADE ON DELETE CASCADE, CONSTRAINT `FK_group_has_contact_group` FOREIGN KEY (`group_id`) REFERENCES `group` (`id`) ON UPDATE CASCADE ON DELETE CASCADE ) COMMENT='N:M' COLLATE='utf8_general_ci' ENGINE=InnoDB AUTO_INCREMENT=55764;
时间: 2024-10-07 10:38:22