由于很多原因,我需要在两个表中拥有相同的数据。我正在启动新系统,并且在短期内我需要让两个系统都运行,问题是旧系统没有那么好的MySQL结构,所以不能保持原样。我不想更改旧的或新的系统配置。我认为他最好的解决方案是在新旧表上放置一些触发器:
DROP TRIGGER IF EXISTS table1_table2;
DELIMITER $$
CREATE TRIGGER `table1_table2` AFTER INSERT ON `table1`
FOR EACH ROW
BEGIN
IF(@disable_triggers != 1) THEN
SET @disable_triggers = 1;
INSERT INTO table2 (value1,value2)
VALUES( NEW.value1, NEW.value2 );
END IF;
SET @disable_triggers = 0;
END$$
DELIMITER ;
DROP TRIGGER IF EXISTS table2_table1;
DELIMITER $$
CREATE TRIGGER `table2_table1` AFTER INSERT ON `table2`
FOR EACH ROW
BEGIN
IF(@disable_triggers != 1) THEN
SET @disable_triggers = 1;
INSERT INTO table1 (value1,value2)
VALUES( NEW.value1, NEW.value2 );
END IF;
SET @disable_triggers = 0;
END$$
DELIMITER ;
首先尝试我创建没有IF条件的触发器并且失败,因为table1被锁定所以第二个触发器无法写入它。我决定添加@disable_triggers全局变量以防止在循环中运行触发器,但在插入后什么也没发生,有什么建议吗?
答案 0 :(得分:0)
感谢e4c5。最佳解决方案是创建VIEW:
CREATE TABLE IF NOT EXISTS `table2` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`t2col1` int(11) DEFAULT 0,
`t2col2` int(11) DEFAULT 0,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
INSERT INTO `table2` (`t2col1`, `t2col2`)
SELECT `t1col1`, `t1col2` FROM `table1`;
DROP TABLE IF EXISTS `table1`;
CREATE OR REPLACE VIEW `table1` AS
SELECT `t2col1` AS `t1col1`, `t2col2` AS `t1col2`
FROM `table2`;
两个查询都有相同的结果
SELECT * FROM `table1`;
和
SELECT * FROM `table2`;
与INSERT
相同