在mysql自动增量中跳过某个数字

时间:2017-01-11 07:24:34

标签: mysql auto-increment

我目前制作了一个简单的记录表,其中recordID作为自动增量主键,问题是,由于宗教原因,我的雇主不会想要包含数字4在recordID中有6个,所以不是每次在记录完成后都检查recordID,是否有更简单的方法来解决我当前的问题?

修改

这是我根据Vanojx1的答案创建的快速测试表。那我做错了什么?

CREATE TABLE `test` (
  `ID` int(11) NOT NULL,
  `value` int(11) NOT NULL
)

DELIMITER $$
CREATE TRIGGER `jump4and6` BEFORE INSERT ON `test` FOR EACH ROW BEGIN
    SET @nextId = (SELECT MAX(`id`) FROM `test`);
    IF (@nextId IN (4,6)) THEN
        SET NEW.id = @nextId + 1;
        SET @nextId = @nextId + 2;
    ELSE
        SET NEW.id = @nextId;
        SET @nextId = @nextId + 1;
    END IF;
    INSERT INTO `test`(`id`) VALUES (@nextId);
    END
$$
DELIMITER ;

ALTER TABLE `test` ADD PRIMARY KEY (`ID`);
ALTER TABLE `test` MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT;

到目前为止一切正常,但当我试图插入一行时:

INSERT INTO `test`(value) VALUES (123456);

这种情况发生了。

#1442 - Can't update table 'test' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

1 个答案:

答案 0 :(得分:-2)

您可以将主键创建为整数,然后在插入之前使用触发器,如下所示:

DELIMITER $$
CREATE TRIGGER jump4and6 
BEFORE INSERT 
ON your_table
  FOR EACH ROW BEGIN
    SET @nextId = (SELECT MAX(current_index) FROM your_table_sequence);
    IF (@nextId IN (4,6)) THEN
        SET NEW.id = @nextId + 1;
        SET @nextId = @nextId + 2;
    ELSE
        SET NEW.id = @nextId;
        SET @nextId = @nextId + 1;
    END IF;
    INSERT INTO your_table_sequence (current_index) VALUES (@nextId);
END$$

您还需要一个表来存储主键序列