mysql中truncate表对auto_increment的影响
2023-08-26 18:47 abce 阅读(245) 评论(0) 编辑 收藏 举报
在mysql中,如果对表执行truncate操作后,会重新设置auto_increment的值,比如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | root@localhost (none)>use abce; Database changed root@localhost abce> create table test(id int not null auto_increment primary key ,age int ); Query OK, 0 rows affected (0.02 sec) root@localhost abce> insert into test(age) values (3),(4),(5); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 root@localhost abce> select * from test; + ----+------+ | id | age | + ----+------+ | 1 | 3 | | 2 | 4 | | 3 | 5 | + ----+------+ 3 rows in set (0.00 sec) root@localhost abce> |
对表执行truncate操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | root@localhost abce> truncate table test; Query OK, 0 rows affected (0.02 sec) root@localhost abce> insert into test(age) values (6),(7),(8); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 root@localhost abce> select * from test; + ----+------+ | id | age | + ----+------+ | 1 | 6 | | 2 | 7 | | 3 | 8 | + ----+------+ 3 rows in set (0.01 sec) root@localhost abce> |
可以看到自增列又从1重新开始了。
但是有时候,因为数据之间的依赖等原因,不希望重复使用相同的自增值作为主键。这个时候可以使用alter table来重新设置auto_increment的值。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | root@localhost abce> truncate table test; Query OK, 0 rows affected (0.03 sec) root@localhost abce> alter table test auto_increment=4; Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0 root@localhost abce> insert into test(age) values (6),(7),(8); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 root@localhost abce> select * from test; + ----+------+ | id | age | + ----+------+ | 4 | 6 | | 5 | 7 | | 6 | 8 | + ----+------+ 3 rows in set (0.01 sec) root@localhost abce> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2020-08-26 PostgreSQL的MVCC(3)--Row Versions
2015-08-26 zabbix客户端安装和配置(windows)
2015-08-26 源码安装Zabbix
2015-08-26 zabbix客户端安装和配置(linux)
2015-08-26 mysqld Can’t start server : Bind on unix socket: Permission denied