MYSQL auto_increment_increment

I would like auto_increment to have two different tables in one mysql database, the first one by a multiple of 1 and the other by 5 - this is possible using the auto_increment function, since I seem to only be able to set auto_increment_increment globally.

If auto_increment_increment is not an option, then what is the way to replicate this

+5
source share
1 answer

Updated version: only one field is used id. This is probably not atomic, so use inside a transaction if you need concurrency:

http://sqlfiddle.com/#!2/a4ed8/1

CREATE TABLE IF NOT EXISTS person (
   id  INT NOT NULL AUTO_INCREMENT,
   PRIMARY KEY ( id )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

CREATE TRIGGER insert_kangaroo_id BEFORE INSERT ON person FOR EACH ROW BEGIN
  DECLARE newid INT;

  SET newid = (SELECT AUTO_INCREMENT
               FROM information_schema.TABLES
               WHERE TABLE_SCHEMA = DATABASE()
               AND TABLE_NAME = 'person'
              );

  IF NEW.id AND NEW.id >= newid THEN
    SET newid = NEW.id;
  END IF;

  SET NEW.id = 5 * CEILING( newid / 5 );
END;

Old, broken "solution" (before insert trigger cannot see the current value of automatic growth):

http://sqlfiddle.com/#!2/f4f9a/1

CREATE TABLE IF NOT EXISTS person (
   secretid  INT NOT NULL AUTO_INCREMENT,
   id        INT NOT NULL,
   PRIMARY KEY ( secretid )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

CREATE TRIGGER update_kangaroo_id BEFORE UPDATE ON person FOR EACH ROW BEGIN
  SET NEW.id = NEW.secretid * 5;
END;

CREATE TRIGGER insert_kangaroo_id BEFORE INSERT ON person FOR EACH ROW BEGIN
  SET NEW.id = NEW.secretid * 5; -- NEW.secretid is empty = unusuable!
END;
+5

All Articles