節選擇《Netkiller MySQL 手札》 spa
AUTO_INCREMENT 並不是按照咱們意願,順序排列,常常會跳過一些數字,例如當插入失敗的時候,再次插入會使用新的值。有時會形成浪費,咱們能夠使用下面SQL從新編排AUTO_INCREMENT序列。 code
SET @newid=0; UPDATE mytable SET id = (SELECT @newid:=@newid+ 1);
使用max()查看最大值,而後使用 alter修改起始位置。 ip
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, ci
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;