我正在从一个系统迁移到另一个系统,在此过程中,我将同时运行两个系统。我需要能够在保持每个表的主键的同时,从一个表到另一个表单向同步。
在这个例子中,我有两个表(A)和(B)。我需要根据公共外键(下面的match1和match2)将表B中的value1和value2(下面)同步到表A.表A将包含除表B之外的其他字段,并且B中的某些字段将不会同步。
如何执行以下操作:
以下是一些演示数据:
DROP TABLE IF EXISTS `a`;
CREATE TABLE IF NOT EXISTS `a` (
`id1` int(10) unsigned NOT NULL,
`match1` int(10) unsigned NOT NULL,
`value1` varchar(255) NOT NULL,
PRIMARY KEY (`id1`)
);
INSERT INTO `a` (`id1`, `match1`, `value1`) VALUES
(1, 1, 'A'),
(2, 2, 'A'),
(3, 3, 'B'),
(4, 4, 'C'),
(5, 5, 'C');
DROP TABLE IF EXISTS `b`;
CREATE TABLE IF NOT EXISTS `b` (
`id2` int(10) unsigned NOT NULL,
`match2` int(10) unsigned NOT NULL,
`value2` varchar(255) NOT NULL,
PRIMARY KEY (`id2`)
);
INSERT INTO `b` (`id2`, `match2`, `value2`) VALUES
(1, 1, 'A'),
(2, 2, 'A'),
(3, 3, 'B'),
(4, 5, 'D'),
(5, 6, 'D'),
(6, 7, 'F');
我目前的方向是在两个表之间创建一个合并表,并相应地构建查询。例如:
create table ab as (select * from a, b);
你有什么建议?
答案 0 :(得分:4)
1.插入已添加到B
的所有内容INSERT INTO a(id1, match1, value1)
SELECT id2, match2, value2
FROM b WHERE NOT EXISTS (SELECT 1 FROM a WHERE a.match1 = b.match2)
2.从A中删除所有已从B
删除的内容DELETE FROM a
WHERE match1 IN (SELECT match1 FROM a INNER JOIN B ON A.match1 = B.match2)
3.使用B
中更改的字段更新A.UPDATE a
SET value1 = (SELECT value2 FROM b WHERE a.match1 = b.match2)
答案 1 :(得分:3)
我构建了一个存储过程来正确合并所有内容。谢谢你的回复。这就是我要去的地方。
BEGIN
DECLARE loop_done INT;
DECLARE orphan varchar(255);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET loop_done=1;
INSERT INTO a(id1, match1, value1)
SELECT '', match2, value2
FROM b WHERE NOT EXISTS (SELECT 1 FROM a WHERE a.match1 = b.match2);
UPDATE a SET value1 = (SELECT value2 FROM b WHERE a.match1 = b.match2);
/* This Delete statement works better for MySQL. */
SET loop_done=0;
SET orphan=null;
SELECT id1 INTO orphan FROM a left join b on (b.match2 = a.match1) where b.id2 is null LIMIT 1;
WHILE (loop_done=0) DO
DELETE FROM a WHERE id1=orphan;
SELECT id1 INTO orphan FROM a left join b on (b.match2 = a.match1) where b.id2 is null LIMIT 1;
END WHILE;
END
答案 2 :(得分:0)
TRUNCATE TABLE A;
INSERT INTO A (id1, match1, value1)
SELECT id2, match2, value2 FROM B;