MySQL插入跳过的ID

时间:2015-12-16 10:33:28

标签: mysql

我有一个mysql表,它有两列,<div class="position--relative"> <div class="position--absolute"> <h1>POSITION THIS TEXT CENTRALLY INSIDE THE CONTAINER</h1> </div> </div>id valueid
auto_increment primary keyvalue

varchar 255

输出

insert into table columns(`id`,`value`)VALUES(,'something1');
insert into table columns(`id`,`value`)VALUES(,'something2');

现在再次插入一个值

+----+---------------+
| id |     value     |
+----+---------------+
|  1 | something1    |
|  2 | something2    |
+----+---------------+

更新表

insert into table columns(`id`,`value`)VALUES(8,'something8');

现在我再次插入一个值

+----+---------------+
| id |     value     |
+----+---------------+
|  1 | something1    |
|  2 | something2    |
|  8 | something8    |
+----+---------------+

最终输出

insert into table columns(`id`,`value`)VALUES(,'something');

但我想要这样的最终输出

+----+---------------+
| id |     value     |
+----+---------------+
|  1 | something1    |
|  2 | something2    |
|  8 | something8    |
|  9 | something     |
+----+---------------+

现在+----+---------------+ | id | value | +----+---------------+ | 1 | something1 | | 2 | something2 | | 8 | something8 | | 3 | something | +----+---------------+ id,进一步插入会创建3 id,依此类推。

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:-1)

我知道这是旧帖子,但我的老兄会帮助别人的

恐怕它不能自动完成,但是,我向客户解决了它,也许有些人会发现它有用:

DECLARE FirstEmptyId int;

SELECT l.id +1 AS 
START 
FROM TableName AS l 
LEFT OUTER JOIN TableName AS r ON l.id +1 = r.id 
WHERE r.id IS NULL 
LIMIT 1 INTO FirstEmptyId;

Insert Into TableName (Id..) Values (FirstEmptyId...)



仍然,您需要考虑的是,除通过自动增加ID值之外,不建议以其他方式插入ID值,这是有原因的:)

考虑仅出于性能目的创建第二列。


祝您好运编码人员!