Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

sql - MYSQL auto_increment_increment

I would like to auto_increment two different tables in a single mysql database, the first by multiples of 1 and the other by 5 is this possible using the auto_increment feature as I seem to only be able to set auto_increment_increment globally.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Updated version: only a single id field is used. This is very 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, non working "solution" (the before insert trigger can't see the current auto increment value):

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...