Mysql 在现有 table 中插入数据。如果已经存在,如何自动给数据新的 id

Mysql insert data in existing table. how to automaticly give the data new id if already exists

我在 2 个不同的数据库中有两个 tables 运行,但结构是相同的。我想将一个 table 的数据导入另一个,但行的 id 是自动递增的。这会导致两个 table 中的 id 具有相同的值,但它们的内容不同。 如何将 table1 的内容插入 table2 并自动将 id 更新为尚不存在的值?

因为 table 包含大约 1000 行,我无法手动更改数字或声明每一行。 像 ON DUPLICATE 'id' AUTO INCREMENT 'id'

INSERT INTO new_db.new_tbl SELECT * FROM old_db.old_tbl;

以上不会为 new_tbl 生成新的 ID。

让我进一步解释一下,我们认为您的两个 table 都启用了 id 作为自动递增。

覆盖自动增量

insert into B select * from A;

  • 如果您在 new_tbl 的 (B) id 列中插入一个值。即,如果您 select 所有列,这将覆盖新 table.
  • 的自动增量

开启自增

insert into B (col1, col2) select col1, col2 from A;

insert into B select 0, col1, col2 from A;

  • 如果你想在 new_tbl 上激活自动增量 (B) 你不能将 ids 传递给 insert stmnt,所以你需要跳过 id(选择你想迁移的列没有 id 列) 或发送 DEFAULT/NULL/0 作为 id。

可能是这样

Hitesh> desc test;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| name  | varchar(200) | YES  |     | NULL    |                |
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

Hitesh> desc test_new;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| name  | varchar(200) | YES  |     | NULL    |                |
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

Hitesh> insert into test_new(name) select name from test;
Query OK, 9 rows affected (0.03 sec)
Records: 9  Duplicates: 0  Warnings: 0

Hitesh> select * from test_new;
+-------------------------+----+
| name                    | id |
+-------------------------+----+
| i am the boss           |  1 |
| You will get soon       |  2 |
| Happy birthday bro      |  3 |
| the beautiful girl      |  4 |
| oyee its sunday         |  5 |
| cat and dog in a park   |  6 |
| dog and cat are playing |  7 |
| cat                     |  8 |
| dog                     |  9 |
+-------------------------+----+
9 rows in set (0.00 sec)