自增列,菜鸟求助关于SQL自增列( 二 )


我采用的方法是将两个自增列值(比如1、2)分为以下三个步骤来实现:
1、先将自增列值为1的修改为0;
2、再将自增列值为2的修改为1;
3、再将自增列值为0的修改为2;
以下两种数据引擎的测试环境均是mysql 5.6 。
数据库引擎为innodb的前提下,具体的mysql测试代码如下:drop table if exists identity_datatable;create table identity_datatable (id int not null AUTO_INCREMENT,name varchar(10) not null,primary key (id)) engine=innodb,default charset=utf8;insert into identity_datatable (id, name)values (1, '1'),(2,'2');insert into identity_datatable (id, name)values (3, '3'),(4,'4');select *from identity_datatable;-- 直接修改不可行-- update identity_datatable-- set id = case when id = 1 then 2 when id = 2 then 1 end-- where id in (1, 2);update identity_datatableset id = 0where id = 1;update identity_datatableset id = 1where id = 2;update identity_datatableset id = 2where id = 0;select *from identity_datatable;
未修改前的数据表结果,如下图:
修改后的数据表结果,如下图:
注意:
1、采用了两个数字进行交换的方法 。
2、引入的中间值最好<=0的数字 。
3、仅仅提供一种解决方法,也可采用sql server平台的修改方法(1、先取消自增属性后变更最后增加自增属性,2、整理T-SQL脚本重新插入----小数据量时可以;3、运营人员手工重新添加,也是数据量小的情况下) 。
数据库引擎为myisam的前提下,具体的mysql测试代码如下:drop table if exists autoincremenet_datatable_myisam;create table autoincremenet_datatable_myisam (tid int not null,id int not null auto_increment,name varchar(20) not null,primary key(id)) engine = myisam, default charset = utf8;insert into autoincremenet_datatable_myisam (tid, id, name)values(1,1,'a'),(2,2,'b'),(3,3,'c'),(4,4,'d');select *from autoincremenet_datatable_myisam;update autoincremenet_datatable_myisamset id = 0;where id = 1;select *from autoincremenet_datatable_myisam;update autoincremenet_datatable_myisamset id = 1;where id = 2;select *from autoincremenet_datatable_myisam;update autoincremenet_datatable_myisamset id = 2;where id = 0;select *from autoincremenet_datatable_myisam;
注意:
1、以上测试中的变更不可行 。
2、疑问“第一条update和其后面的select确实看到了修改后的值,但是随后的sql继续执行,均报错却又恢复了未修改之前的状态“,这个还不清楚,需要继续研究 。
Oracle平台的没有接触,不晓得,熟悉oracle平台的博友针对其自增列的变更做个测试或给出个总结 。
mysql innodb支持自增列吗

自增列,菜鸟求助关于SQL自增列

文章插图
对于mysql数据库表的引擎是innodb的,是完全支持自增列的
具体操作可以通过sql设定,也可根据具体的软件进行设定,如下图:
设置主键
勾选自动递增
保存之后,再往此表插入数据时,可不需填写主键的信息 。