如何使用sqlite id自动递增?

7ivaypg9  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(360)

我´我通过id访问数据库中的项目,但当我删除行,然后插入某些内容时,id也会增加,因此id之间会留有间隙。
e、 g.项1(id=1)、项2(id=2)、项3(id=3)==删除+插入==>项1(id=1)、项2(id=2)、项3(id=4)
当我想通过项目的ID访问项目时,这里的解决方法是什么?

7gcisfzg

7gcisfzg1#

包括三件事:
管理自己的增量
更改自动增量序列
不要担心差距

自行管理增量(无自动增量)

你不必像尼古拉斯在评论中提到的那样使用自动递增id。您可以手动输入,也可以按以下方式进行内联查询:

create table test (id, name);
insert into test select coalesce(max(id)+1, 1), 'john' from test;
select * from test;
id          name      
----------  ----------
1           john      

insert into test select coalesce(max(id)+1, 1), 'mary' from test;
select * from test;
id          name      
----------  ----------
1           john      
2           mary      

insert into test select coalesce(max(id)+1, 1), 'abcdefg' from test;
sqlite> select * from test;
id          name      
----------  ----------
1           john      
2           mary      
3           abcdefg

delete from test where id = 3;
insert into test select coalesce(max(id)+1, 1), 'rubio' from test;
sqlite> select * from test;
id          name      
----------  ----------
1           john      
2           mary      
3           rubio

使用自动递增,但重置下一个值

您可以使用整数自动递增字段,并将下一个序列重置为下一个值,以便不会留下这样的间隙:

create table test1 (id integer primary key autoincrement, name text);
insert into test1 (name) values ('john');
insert into test1 (name) values ('mary');

-- let's create a gap
delete from test1 where id = 2;

-- let's fill the gap back up
update sqlite_sequence set seq = (select max(id) FROM test1) where name='test1';
insert into test1 (name) values ('tony');
select * from test1;
id          name      
----------  ----------
1           john      
2           tony

请参阅以下文档:https://sqlite.org/fileformat2.html#seqtab

不在乎完美的身份证

当你想让你的身份证是连续的,我会说-不要担心差距。您将为每一行提供一个id以唯一地标识它们。如果第一行唯一标识为100,第二行唯一标识为-90,那又怎样?就这样吧。
我的建议是保持自动递增的方式。如果删除表中间的一行,就可以了。不要担心差距。

anauzrmj

anauzrmj2#

id不必与项目编号相同。每个id都是唯一的,所以item3(id==1)还是(id==3)无关紧要。id仍然是唯一的。

相关问题