这是我的表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 |
+--------+---------+
答案 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 ║
╚════════╩═════════╝