【问题标题】:Start auto_increment value not working when populating table with data from another table in MySQL使用 MySQL 中另一个表中的数据填充表时,启动 auto_increment 值不起作用
【发布时间】:2013-02-23 17:37:01
【问题描述】:

我想用另一个表中的数据创建一个表,以便将 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 |
+----+---------+---------+----------+-------------------+

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

【问题讨论】:

标签: mysql primary-key auto-increment


【解决方案1】:

我刚刚发现出了什么问题,在截断表格后,它似乎失去了对 auto_increment 起始值的引用。为了再次正确设置 auto_increment 值,我不得不再次执行 alter table 查询:

alter table table_temp auto_increment = 40499;

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 2014-09-23
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 2022-08-22
    • 1970-01-01
    相关资源
    最近更新 更多