让我们举个例子:
id是主键和auto_increment
| id | name | area |
===============
| 1 | apple | garden |
| 2 | nuts | forest |
| 3 | tomato | garden |
id是主键和auto_increment
| id | color | parent_id |
=====================
| 1 | green | 1 |
| 2 | braun | 2 |
| 3 | red | 3 |
通过以下代码,我将表= 1中的条目复制为表=“花园”作为新条目,其他区域为“种植园”。这还将为此条目生成一个新的ID。我的问题或疑问是如何使用正确/新的parent_id(Table1.id = Table2.parent_id)复制Table2的条目。
有人有想法吗?
CREATE TABLE tmp AS SELECT * FROM Table1;
ALTER TABLE tmp CHANGE id id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY;
UPDATE tmp SET area = 'plantation' WHERE area = 'garden';
INSERT INTO Table1 (name, area)
SELECT name
, area
FROM tmp
WHERE area='plantation';
DROP TABLE tmp;
结果必须是这样的:
id是主键和auto_increment
| id | name | area |
===============
| 1 | apple | garden |
| 2 | nuts | forest |
| 3 | tomato | garden |
| 4 | apple | plantation |
| 5 | tomato | plantation |
id是主键和auto_increment
| id | color | parent_id |
=====================
| 1 | green | 1 |
| 2 | braun | 2 |
| 3 | red | 3 |
| 4 | green | 4 |
| 5 | red | 5 |