Is there a way to specify a custom auto increment starting value and a custom auto increment increment value for only one MySQL table?
I couldn't find a clear answer to my question. There seem to be two global variables auto_increment_increment and auto_increment_offset but I need it for one table only. Another site suggested using AUTO_INCREMENT(<offset>,<increment>)
but this approach just triggered MySQL errors.
So is there a way to do this?
You can't change the step on a per table basis in MySQL. Running SET @@auto_increment_increment=2;
or changing the startup value will affect all tables and databases on the server.
As far as I can tell you have two options:
You could consider a trigger that performs the maths you want and sets a custom value to another field.
CREATE TRIGGER trigger
BEFORE INSERT ON my_table
FOR EACH ROW BEGIN
SET NEW.id2 = NEW.id * 2;
END
You can execute this SQL, say if you wanted to start it at 3:
ALTER TABLE foo AUTO_INCREMENT = 3;
As others pointed out, I don't believe you can do both, however.
You can change the current value to be applied to the next inserted row via:
ALTER TABLE table AUTO_INCREMENT = ?;
The increment value can be set via the auto_increment_increment
server variable.
Unfortunately this will effect all databases/tables on the server if set in Global context.
You can set this variable on a session-specific basis. So, if you wanted to use a specific set of DB connections, to which you set the value on a session basis, that is possible. This might be a bit unwieldy to manage as you would, in essence, need a distinct connection (or pool of connections) just to update this single table.
I have found the way to change auto_increment, just alter table. I have to the problem when migrate old database to new system (from Heroku to Amazon), but have to keep all old data (not change id), but every day a hundred thousand happen, so how can I keep data and duplicate data do not happen, what I did:
Ex:
- Create table:
CREATE TABLE `test`.`table_inc` (
`idtable_inc_id` INT NOT NULL AUTO_INCREMENT,
`table_inccol` VARCHAR(45) NULL,
PRIMARY KEY (`idtable_inc_id`));
- Alter table (to remove auto increment)
ALTER TABLE `test`.`table_inc`
CHANGE COLUMN `idtable_inc_id` `idtable_inc_id` INT(11) NOT NULL ;
I have found another answer for this solution
> mysqldump -u root -p database_heroku | sed 's/ AUTO_INCREMENT=[0-9]*\b/ AUTO_INCREMENT=1100001/' > /new_increment_with_data_heroku_database.sql
Ref: http://melikedev.com/2011/06/01/mysql-remove-auto_increment-from-schema-dumps-mysqldump/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.