如何从另一个 table 设置 AUTO_INCREMENT

How to set AUTO_INCREMENT from another table

我如何在 CREATE TABLEALTER TABLE 上设置另一个 table 上的 AUTO_INCREMENT

我发现了这个问题,但没有解决我的问题: How to Reset an MySQL AutoIncrement using a MAX value from another table?

我也试过这个:

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

这个:

ALTER TABLE `table_name` AUTO_INCREMENT=(SELECT `AUTO_INCREMENT` FROM  `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA` = 'database_name' AND `TABLE_NAME` = 'another_table_name');

这个:

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

还有这个:

ALTER TABLE `table_name` AUTO_INCREMENT=(SELECT (MAX(`id`)+1) FROM `another_table_name`);

此代码将为您创建程序:

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;

然后你可以调用CALL tbl_wth_ai(2);传递括号内的参数。

例如:

CALL tbl_wth_ai((SELECT id FROM `ttest` WHERE c1='b'));

这很好用:

DELIMITER $$
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 $$
DELIMITER ;

CALL tbl_wth_ai((SELECT MAX(`id`)+1 FROM `another_table_name`));
DROP PROCEDURE IF EXISTS tbl_wth_ai;
SELECT `AUTO_INCREMENT` INTO @AutoInc
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'my_db' AND TABLE_NAME = 'old_table';

SET @s:=CONCAT('ALTER TABLE `my_db`.`new_table` AUTO_INCREMENT=', @AutoInc);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;