PostgreSQL-表中的下一个序列值 [英] PostgreSQL - next serial value in a table

查看:160
本文介绍了PostgreSQL-表中的下一个序列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题,假设我们有一张桌子:

I have a simple question, suppose we have a table:

 id   A   B
 1   Jon  Doe
 2   Foo  Bar

有没有办法知道,这是下一个id的增量情况3?
数据库是PostgreSQL!

Is there a way to know, which is the next id's increment, in this case 3 ? Database is PostgreSQL!

Tnx很多!

推荐答案

如果您要索取ID并返回ID,则可以使用 nextval() ,它将在不插入任何数据的情况下推进序列。

If you want to claim an ID and return it, you can use nextval(), which advances the sequence without inserting any data.

请注意,如果这是 SERIAL 列,您需要根据表和列名称查找序列的名称,如下所示:

Note that if this is a SERIAL column, you need to find the sequence's name based on the table and column name, as follows:

Select nextval(pg_get_serial_sequence('my_table', 'id')) as new_id;

没有铸铁保证,您会看到这些ID顺序返回(顺序按顺序生成它们,但是多个会话可以声明一个ID且尚未使用它,或者回滚 INSERT 并且该ID将不会重复使用),但是可以保证它们将是唯一的,这通常很重要。

There is no cast-iron guarantee that you'll see these IDs come back in order (the sequence generates them in order, but multiple sessions can claim an ID and not use it yet, or roll back an INSERT and the ID will not be reused) but there is a guarantee that they will be unique, which is normally the important thing.

如果您经常这样做而实际上没有使用ID,则最终将用尽32的所有可能值。 -bit integer 列(即达到最大可表示整数),但是如果仅在极有可能使用时才使用该ID,则实际上应该插入具有该ID的行好吧。

If you do this often without actually using the ID, you will eventually use up all the possible values of a 32-bit integer column (i.e. reach the maximum representable integer), but if you use it only when there's a high chance you will actually be inserting a row with that ID it should be OK.

这篇关于PostgreSQL-表中的下一个序列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆