MySql id 设定为主键不自增后,再给 sort 字段增加自增属性

时间:2023-03-10 01:39:53
MySql id 设定为主键不自增后,再给 sort 字段增加自增属性
  • 需求

    id 已经被设置为主键,但是没有给它设置 自增 属性。sort 起到一个排序的作用,需要给它设置一个 自增 属性

  • 加自增属性的前提

    1. 表中的属性没有增加自增
    2. 赋予自增属性的字段,必须带有 索引
  • SQL

alter table test MODIFY sort int(11) not Null;   #不要设置default 0,会报错:Invalid default value for ‘id’
alter table test add unique idx_sort(`sort`); #设置唯一索引,方便加自增长属性
alter table test modify column sort int(11) not null AUTO_INCREMENT; #这句执行成功