如何使用另一个表中的 MAX 值重置 MySQL AutoIncrement?

2021-11-30 00:00:00 sql reset mysql auto-increment

我知道这行不通.我以各种形式尝试过,但每次都失败了.实现以下结果的最简单方法是什么?

I know this won't work. I tried it in various forms and failed all times. What is the simplest way to achieve the following result?

ALTER TABLE XYZ AUTO_INCREMENT = (select max(ID) from ABC);

这非常适合自动化项目.

This is great for automation projects.

SELECT @max := (max(ID)+1) from ABC;        -> This works!
select ID from ABC where ID = (@max-1);     -> This works!
ALTER TABLE XYZ AUTO_INCREMENT = (@max+1);  -> This fails :( Why?

推荐答案

使用 准备语句:

  SELECT @max := MAX(ID)+ 1 FROM ABC;

  PREPARE stmt FROM 'ALTER TABLE ABC AUTO_INCREMENT = ?';
  EXECUTE stmt USING @max;

  DEALLOCATE PREPARE stmt;

相关文章