使用MySQL中另一个表的数据填充表时,启动auto_increment值不起作用

时间:2013-03-08 08:20:21

标签: mysql primary-key auto-increment

我想创建一个包含来自另一个表的数据的表,以便将id设置为某个auto_increment起始值。

这是我想用另一个表中的数据填充的表:

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| city      | varchar(255) | YES  |     | NULL    |                |
| state     | varchar(255) | YES  |     | NULL    |                |
| state_id  | int(11)      | YES  |     | NULL    |                |
| city_slug | varchar(255) | YES  |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

执行此查询后:

alter table table_temp auto_increment = 40499;

如果我做一个假插入:

insert into table_temp (city, state, state_id, city_slug) values (1, 1, 1, 1);

它按预期执行,即id以值40499

开头
select * from table_temp;

+-------+------+-------+----------+-----------+
| id    | city | state | state_id | city_slug |
+-------+------+-------+----------+-----------+
| 40499 | 1    | 1     |        1 | 1         |
+-------+------+-------+----------+-----------+

截断表并再次执行auto_increment的alter table查询后,我尝试用另一个表中的数据填充同一个表:

insert into table_temp (city, state, state_id, city_slug) select city, state, state_id, city_slug from final_location;

但是,id的默认id值为1:

select * from table_temp limit 10;

+----+---------+---------+----------+-------------------+
| id | city    | state   | state_id | city_slug         |
+----+---------+---------+----------+-------------------+
|  1 | Abatiá  | Paraná  |      242 | all-cidade-abatia |
+----+---------+---------+----------+-------------------+

有关如何解决此问题的任何建议吗?

1 个答案:

答案 0 :(得分:1)

我刚刚发现错误,截断表后似乎松散了auto_increment起始值的引用。我不得不再次执行alter table查询,以便再次正确设置auto_increment值:

alter table table_temp auto_increment = 40499;