你可以这样做:
school_id
在目标school
表中找到 MAX -
SELECT MAX(school_id) INTO @max_school_id FROM school;
更改school_id
源表 ( school
, ) 中的所有值 -从上一点class
添加 MAX -school_id
UPDATE school SET school_id = school_id + @max_school_id + 1;
向外键添加操作可能非常有用ON UPDATE CASCADE
,它将有助于school_id
自动更改子表,例如 -
ALTER TABLE class
DROP FOREIGN KEY FK_name;
ALTER TABLE class
ADD CONSTRAINT FK_name FOREIGN KEY (school_id)
REFERENCES school(school_id) ON UPDATE CASCADE;
解释和例子:
创建源表:
CREATE TABLE school(
school_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20)
);
INSERT INTO school (school_id, name) VALUES
(1, 'Middle1'),
(2, 'Middle2'),
(3, 'Middle3'),
(15, 'Middle');
CREATE TABLE class(
class_id INT(11) NOT NULL,
school_id INT(11) DEFAULT NULL,
name VARCHAR(20) DEFAULT NULL,
PRIMARY KEY (class_id),
CONSTRAINT FK_class_school_school_id FOREIGN KEY (school_id)
REFERENCES school (school_id) ON DELETE RESTRICT ON UPDATE CASCADE
)
ENGINE = INNODB;
INSERT INTO class (class_id, school_id, name) VALUES (11, 1, 'Sample1');
INSERT INTO class (class_id, school_id, name) VALUES (12, 15, 'Sample');
创建目标表:
CREATE TABLE school(
school_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20)
);
INSERT INTO school (school_id, name) VALUES
(1, 'Top'),
(2, 'Middle'),
(3, 'Bottom'),
(15, 'Top');
CREATE TABLE class(
class_id INT(11) NOT NULL,
school_id INT(11) DEFAULT NULL,
name VARCHAR(20) DEFAULT NULL,
PRIMARY KEY (class_id),
CONSTRAINT FK_class_school_school_id FOREIGN KEY (school_id)
REFERENCES school (school_id) ON DELETE RESTRICT ON UPDATE CASCADE
)
ENGINE = INNODB;
INSERT INTO class (class_id, school_id, name) VALUES (10, 2, 'Sample2');
INSERT INTO class (class_id, school_id, name) VALUES (12, 15, 'Sample');
更新源表,增加 id 值:
我们应该更新所有唯一值,在我们的例子中,我们必须更新表和表class_id
中的值。class
school_id
school
class_id
查找目标class
表的最大值
SELECT MAX(class_id) + 1000 FROM class; -- This will return => 1012
增加所有 SOURCEclass_id
值class_id + 1012
UPDATE class SET class_id = class_id + 1012;
school_id
查找目标school
表的最大值
SELECT max(school_id) + 1000 FROM school; -- This will return =>1015
增加所有 SOURCEschool_id
值school_id + 1015
UPDATE school SET school_id = school_id + 1015;
就这些。我们可以转储源表:
INSERT INTO school VALUES
(1016, 'Middle1'),
(1017, 'Middle2'),
(1018, 'Middle3'),
(1030, 'Middle');
INSERT INTO class VALUES
(1023, 1016, 'Sample1'),
(1024, 1030, 'Sample');
现在我们可以轻松地针对目标数据库运行此脚本。