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
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.