1、问题显示:
今天扫描二维码添加数据的时候,发现添加不了数据了,打开数据库发现自增长的ID断层的情况。(自己的数据库已经处理了,下面截图为网友的数据库截图)
少了ID为5和6的数据,经过确认,是postgresql对高并发处理机制导致的,
在pg中,每次新增数据,都会将一个ID锁定到这条数据上,如果这条数据因为某些原因插入失败(主键重复等),那么这个ID也不会再赋予新的数据,因此出现ID跳过的现象,官方解释:
If transactions rollback, the serial value assigned during the rolled
back transaction is skipped. This has been discussed many times, it's
a tradeoff between losing some #s now and again and taking a huge
performance and code complexity hit to avoid it.
If you absolutely need consecutive #s, then serial is not for you and
you should implement your own method of acquiring sequential numbers.
2、解决方式:自己试了网上几种方式,发现下面这种能处理,查询添加这个sql。但是有个缺点:偶尔也添加不了,但是多试几次就可以了。不会出现一直新增不了数据的情况。如果网友有其他更好的方法,请留言讨论。(col_store_factory_id_seq)为序列,(col_store_factory)为表名。
SELECT setval('col_store_factory_id_seq', (SELECT MAX(id) FROM col_store_factory));