如何在mysql中复制表行?

时间:2016-03-11 10:55:00

标签: mysql

这是我的表farm

+--------+
| animal |
+--------+
| cat    |
| monkey |
| bird   |
| dog    |
| horse  |
+--------+

我想要对行animal进行精确复制。所以我的表应该是这样的:

+--------+---------+
| animal | animal2 |
+--------+---------+
| cat    | cat     |
| monkey | monkey  |
| bird   | bird    |
| dog    | dog     |
| horse  | horse   |
+--------+---------+

我试过

INSERT INTO `farm` (`animal2`) SELECT `animal` FROM `animals`

但是会发生什么:

+--------+---------+
| animal | animal2 |
+--------+---------+
| cat    |         |
| monkey |         |
| bird   |         |
| dog    |         |
| horse  |         |
|        | cat     |
|        | monkey  |
|        | bird    |
|        | dog     |
|        | horse   |
+--------+---------+

2 个答案:

答案 0 :(得分:3)

为避免删除表中不相关的数据,请使用以下方法。

DELETE FROM `farm` WHERE `animal1` IN (SELECT `animal` FROM `animals`);
INSERT INTO `farm` (`animal`, `animal2`) SELECT `animal`, `animal` FROM `animals`;

答案 1 :(得分:1)

首先,您应该添加新列(具有相同的数据类型)和NULL

ALTER TABLE `farm` ADD `animal2` VARCHAR(100);

然后只需更新:

UPDATE `farm` SET `animal2` = `animal`;

如果您需要使用NOT NULL再次使用NOT NULL属性更改表。

LiveDemo

输出:

╔════════╦═════════╗
║ animal ║ animal2 ║
╠════════╬═════════╣
║ cat    ║ cat     ║
║ monkey ║ monkey  ║
║ bird   ║ bird    ║
║ dog    ║ dog     ║
║ horse  ║ horse   ║
╚════════╩═════════╝