Search code examples
mysqlauto-incrementcreate-tablealter-table

How to set AUTO_INCREMENT from another table


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`);

Solution

  • 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'));