How can I set the AUTO_INCREMENT
on CREATE TABLE
or ALTER TABLE
from another table?
I found this question, but not solved my issue: How to Reset an MySQL AutoIncrement using a MAX value from another table?
I also tried this:
CREATE TABLE IF NOT EXISTS `table_name` (
`id` mediumint(6) unsigned NOT NULL AUTO_INCREMENT,
`columnOne` tinyint(1) NOT NULL,
`columnTwo` int(12) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=(SELECT `AUTO_INCREMENT` FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA` = 'database_name' AND `TABLE_NAME` = 'another_table_name');
this:
ALTER TABLE `table_name` AUTO_INCREMENT=(SELECT `AUTO_INCREMENT` FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA` = 'database_name' AND `TABLE_NAME` = 'another_table_name');
this:
CREATE TABLE IF NOT EXISTS `table_name` (
`id` mediumint(6) unsigned NOT NULL AUTO_INCREMENT,
`columnOne` tinyint(1) NOT NULL,
`columnTwo` int(12) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=(SELECT (MAX(`id`)+1) FROM `another_table_name`);
and this:
ALTER TABLE `table_name` AUTO_INCREMENT=(SELECT (MAX(`id`)+1) FROM `another_table_name`);
If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
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.
This code will create procedure for you:
CREATE PROCEDURE `tbl_wth_ai`(IN `ai_to_start` INT)
BEGIN
SET @s=CONCAT('CREATE TABLE IF NOT EXISTS `table_name` (
`id` mediumint(6) unsigned NOT NULL AUTO_INCREMENT,
`columnOne` tinyint(1) NOT NULL,
`columnTwo` int(12) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT = ', `ai_to_start`);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
Then you may call CALL tbl_wth_ai(2);
passing the parameter inside the brackets.
For example:
CALL tbl_wth_ai((SELECT id FROM `ttest` WHERE c1='b'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With