Increment Table ID Field with Bitwise Counting

后端 未结 1 1502
慢半拍i
慢半拍i 2021-01-28 06:27

I am working on a project where I need my ID column to be a power of 2 (1,2,4,8,16..). I know that we cannot offset the auto_increment but for simple a

1条回答
  •  深忆病人
    2021-01-28 07:17

    To work around all the issues above, I was able to construct the following which works great!

    DELIMITER $$
    CREATE TRIGGER testbitcompatid BEFORE INSERT ON Table
        FOR EACH ROW 
        BEGIN
            SET @LAST_ROW = (SELECT MAX(id) FROM Table);
            SET NEW.id = CASE WHEN @LAST_ROW IS NULL THEN 1 ELSE @LAST_ROW * 2 END;
    
        END;
    $$
    DELIMITER ;
    

    Pretty much, we take the highest id, grab the log(2) of it which gives us the corresponding AUTO_INCREMENT id. We then add 1, and power that up to 2.

    I hope this helps prevent some headache down the road for others.

    0 讨论(0)
提交回复
热议问题