首页 > 解决方案 > 从特定开始显式插入自动增量列号

问题描述

我正在尝试在同一个表中复制一些数据,但愿意从特定的数字序列中添加一个 id 列。请记住 PK(id 列)是自动递增的。

INSERT INTO `switch_person` (PK, `PTPK`, `EmployeeNamePK`, `SwitchTime`, `Half`, `date`, `Month`, `Year`, `SwitchDate`, `hoursWorked`, `LeadBy`, `Info`, `EmpDaysStatusId`, `TaskPK`, `TaskAssignCompletionId`, `SpendDays`, `LeaveId`, `Comments`)
select [Number will be here with each record increment], `PTPK`, `EmployeeNamePK`, `SwitchTime`, 1, `date`, `Month`, `Year`, `SwitchDate`, `hoursWorked`, `LeadBy`, `Info`, `EmpDaysStatusId`, `TaskPK`, `TaskAssignCompletionId`, `SpendDays`, `LeaveId`, `Comments`
from switch_person
where SwitchDate = '2021-08-17'
and Half = 2

就像我想用 687477 号添加 PK 并且下一条记录应该添加 687478 然后 687479

标签: mysqlsql

解决方案


首先将增量设置为 687477

ALTER TABLE switch_person AUTO_INCREMENT=687477;

然后运行您的插入,不指定 pk 它将使用自动增量并为下一次插入增加它。

INSERT INTO `switch_person` (`PTPK`, `EmployeeNamePK`, `SwitchTime`, `Half`, `date`, `Month`, `Year`, `SwitchDate`, `hoursWorked`, `LeadBy`, `Info`, `EmpDaysStatusId`, `TaskPK`, `TaskAssignCompletionId`, `SpendDays`, `LeaveId`, `Comments`)
select `PTPK`, `EmployeeNamePK`, `SwitchTime`, 1, `date`, `Month`, `Year`, `SwitchDate`, `hoursWorked`, `LeadBy`, `Info`, `EmpDaysStatusId`, `TaskPK`, `TaskAssignCompletionId`, `SpendDays`, `LeaveId`, `Comments`
from switch_person
where SwitchDate = '2021-08-17'
and Half = 2

推荐阅读