【问题标题】:AUTO_INCREMENT primary key and update its references in other tables at the same timeAUTO_INCREMENT 主键并同时更新其在其他表中的引用
【发布时间】:2018-05-01 13:44:25
【问题描述】:

我有一个主学生表和多个其他表,其中包含学生 ID 引用。我需要通过

更改主学生表中的student_id(这是一个主键)
ALTER TABLE `student` AUTO_INCREMENT = 72805;

并替换以72805 开头的所有表(包括主学生表)中的所有 student_id 引用。有没有办法做到这一点?

学生桌

student_id   student_name
    1           Sarah
    2           John
    3           Peter

类表

class_id    student_id
        340         2
        432         1
        127         3

活动

activity_id     student_id
    105             1
    106             1
    205             2
    207             2
    217             3

书桌

boook_id    student_id
    105         1
    106         1
    205         2
    207         2
    217         3

【问题讨论】:

  • 密钥是否使用ON UPDATE CASCADE?

标签: mysql sql


【解决方案1】:

您需要删除 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`);

【讨论】:

  • 工作得很好!谢谢
猜你喜欢
  • 2011-12-09
  • 1970-01-01
  • 1970-01-01
  • 2014-07-02
  • 2021-08-26
  • 2011-06-11
  • 2015-09-19
  • 2011-10-01
  • 1970-01-01
相关资源
最近更新 更多