Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL auto_increment_increment

Tags:

sql

mysql

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

like image 853
Purple Hexagon Avatar asked Jul 03 '12 09:07

Purple Hexagon


People also ask

How do I make a column auto increment in MySQL?

Syntax. In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name.

How can I get auto increment ID?

To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT. Creating a table, with “id” as auto-increment. Inserting records into the table. To display all the records.

How do I add an auto increment to an existing column?

Here's the syntax of ALTER TABLE statement, ALTER TABLE table_name MODIFY column_name INT NOT NULL AUTO_INCREMENT PRIMARY KEY; In the above statement, you need to specify the table_name and column_name. Here's the SQL statement to add AUTO INCREMENT constraint to id column.

Is primary key auto increment by default?

No. A primary key must be unique and that has to be 100% guaranteed, and NON NULL A primary key should be stable if ever possible and not change.


1 Answers

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;
like image 99
biziclop Avatar answered Oct 29 '22 18:10

biziclop