我对如何复制表格一无所知。但这是我的问题,我有table_1有5列并且有数据,然后我有table_2有10列,没有数据。 table_1中的所有列在table_2中都是相同的,这意味着table_2中只有5个列在table_1中相同,所以我想将table_2中的其他5列复制到table_1,但它不会影响table_1上的数据。我怎样才能做到这一点?提前谢谢。
的预期输出答案 0 :(得分:1)
以下是如何复制/复制表及其中的所有信息。
答案 1 :(得分:1)
您可以使用ON DUPLICATE KEY UPDATE
插入来更新现有行。但是,这基于唯一键约束。这意味着您必须创建约束或更新现有约束。
确实需要在5列中存在唯一数据。 因此,当插入来自table_2的行并且违反了唯一约束时,它将更新行而不是完成插入。
ALTER TABLE table_1
ADD UNIQUE INDEX ix_unique (col_1, col_2, col_3, col_4, col_5);
INSERT INTO table_1(col_1, col_2, col_3, col_4, col_5,
col_6, col_7, col_8, col_9, col_10)
SELECT t.col_1, t.col_2, t.col_3, t.col_4, t.col_5,
t.col_6, t.col_7, t.col_8, t.col_9, t.col_10
FROM table_2 t
ON DUPLICATE KEY UPDATE col_6 = t.col_6, col_7 = t.col_7, col_8 = t.col_8, col_9 = t.col_9, col_10 = t.col_10;
INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE
我能够在mysql 5.7上重现这个,我从5.5开始就看到了这个功能。
这是我运行的脚本。
CREATE TABLE IF NOT EXISTS `table_1` (
`col_1` int(10) unsigned NULL,
`col_2` int(10) unsigned NULL,
`col_3` int(10) unsigned NULL,
`col_4` int(10) unsigned NULL,
`col_5` int(10) unsigned NULL,
`col_6` int(10) unsigned NULL,
`col_7` int(10) unsigned NULL,
`col_8` int(10) unsigned NULL,
`col_9` int(10) unsigned NULL,
`col_10` int(10) unsigned NULL,
UNIQUE INDEX ix_unique (col_1, col_2, col_3, col_4, col_5)
);
CREATE TABLE IF NOT EXISTS `table_2` (
`col_1` int(10) unsigned NULL,
`col_2` int(10) unsigned NULL,
`col_3` int(10) unsigned NULL,
`col_4` int(10) unsigned NULL,
`col_5` int(10) unsigned NULL,
`col_6` int(10) unsigned NULL,
`col_7` int(10) unsigned NULL,
`col_8` int(10) unsigned NULL,
`col_9` int(10) unsigned NULL,
`col_10` int(10) unsigned NULL
);
INSERT INTO table_1 (`col_1`, `col_2`, `col_3`, `col_4`, `col_5`)
VALUES
(1, 1, 1, 1, 1),
(2, 2, 2, 2, 2),
(3, 3, 3, 3, 3),
(4, 4, 4, 4, 4),
(5, 5, 5, 5, 5),
(6, 6, 6, 6, 6),
(7, 7, 7, 7, 7),
(8, 8, 8, 8, 8),
(9, 9, 9, 9, 9),
(10, 10, 10, 10, 10);
INSERT INTO table_2 (`col_1`, `col_2`, `col_3`, `col_4`, `col_5`, `col_6`, `col_7`, `col_8`, `col_9`, `col_10`)
VALUES
(1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
(2, 2, 2, 2, 2, 2, 2, 2, 2, 2),
(3, 3, 3, 3, 3, 3, 3, 3, 3, 3),
(4, 4, 4, 4, 4, 4, 4, 4, 4, 4),
(5, 5, 5, 5, 5, 5, 5, 5, 5, 5),
(6, 6, 6, 6, 6, 6, 6, 6, 6, 6),
(7, 7, 7, 7, 7, 7, 7, 7, 7, 7),
(8, 8, 8, 8, 8, 8, 8, 8, 8, 8),
(9, 9, 9, 9, 9, 9, 9, 9, 9, 9),
(10, 10, 10, 10, 10, 10, 10, 10, 10, 10);
INSERT INTO table_1(col_1, col_2, col_3, col_4, col_5,
col_6, col_7, col_8, col_9, col_10)
SELECT t.col_1, t.col_2, t.col_3, t.col_4, t.col_5,
t.col_6, t.col_7, t.col_8, t.col_9, t.col_10
FROM table_2 t
ON DUPLICATE KEY UPDATE col_6 = t.col_6, col_7 = t.col_7, col_8 = t.col_8, col_9 = t.col_9, col_10 = t.col_10;