您需要删除 Class、Activity 和 Books 的外键约束,并使用 ON UPDATE CASCADE 子句重新创建它们。
SHOW CREATE TABLE class;
SHOW CREATE TABLE activity;
SHOW CREATE TABLE books;
这些将显示外键约束的名称。您需要 student_id 上的外键约束的名称。
ALTER TABLE class DROP FOREIGN KEY [enter the foreign key name here], ADD CONSTRAINT [enter foreign key name here] FOREIGN KEY (`student_id`) REFERENCES student (`student_id`) ON UPDATE CASCADE;
ALTER TABLE activity DROP FOREIGN KEY [enter the foreign key name here], ADD CONSTRAINT [enter foreign key name here] FOREIGN KEY (`student_id`) REFERENCES student (`student_id`) ON UPDATE CASCADE;
ALTER TABLE books DROP FOREIGN KEY [enter the foreign key name here], ADD CONSTRAINT [enter foreign key name here] FOREIGN KEY (`student_id`) REFERENCES student (`student_id`) ON UPDATE CASCADE;
这样做会告诉 MySQL,如果您更新学生表上的 student_id 以更新引用表中的值。取决于您的业务逻辑,取决于您是否保留 ON UPDATE CASCADE 子句。我从不亲自使用它,因为您很少更新主键。
如果您没有外键,则应删除 drop 子句并保留 add 子句。
结构已经到位,现在可以更新您的 student_id 并将其级联到其他表。
UPDATE student SET student_id = student_id + 72804; -- Minus 1 because the values already in here start at 1, not 0.
您不想将 auto_increment 设置为 72805,因为这是您希望第一条记录开始的位置,而您现在有一行占据该值。
此查询将为您提供您现在应该将 auto_increment 值设置为的值。
SELECT MAX(student_id) + 1 FROM student;
现在运行您的 ALTER 表语句并将 auto_increment 设置为您从上述查询中收到的值。
ALTER TABLE student AUTO_INCREMENT = [Value you receive from the SELECT MAX()].
完成后,我会删除并重新创建外键没有 ON UPDATE CASCADE。
ALTER TABLE class DROP FOREIGN KEY [enter the foreign key name here], ADD CONSTRAINT [enter foreign key name here] FOREIGN KEY (`student_id`) REFERENCES student (`student_id`);
ALTER TABLE activity DROP FOREIGN KEY [enter the foreign key name here], ADD CONSTRAINT [enter foreign key name here] FOREIGN KEY (`student_id`) REFERENCES student (`student_id`);
ALTER TABLE books DROP FOREIGN KEY [enter the foreign key name here], ADD CONSTRAINT [enter foreign key name here] FOREIGN KEY (`student_id`) REFERENCES student (`student_id`);