加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

PostgreSQL SEQUENCE

发布时间:2020-12-13 17:20:23 所属栏目:百科 来源:网络整理
导读:PostgreSQL有数据类型 smallserial,serial,bigserial,它们都不是真正的类型,是依赖与一个序列的自动增长的且不为null的类型。 create table tb10( id serial ); 等价于下面的语句: create sequence tb10_id_seq; create table tb10( id integer not null

PostgreSQL有数据类型 smallserial,serial,bigserial,它们都不是真正的类型,是依赖与一个序列的自动增长的且不为null的类型。

create table tb10( id serial );

等价于下面的语句:

create sequence tb10_id_seq;
create table tb10( id integer not null default nextval('tb10_id_seq');
);
alter seqence tb10_id_seq owner by tb10.id;

第三句的意思是创建的序列从属于tb10的id字段,这样删除id字段之后,该序列也会自动被删除。

NOTE:序列没有保证唯一或者主键,如果需要,需自行添加。
在往表中插入数据的时候,有的时候会碰到如下问题:

postgres=# insert into tb10(name) values('bb');
ERROR:  duplicate key value violates unique constraint "tb10_pkey"
DETAIL:  Key (id)=(1) already exists.

解释:

postgres=# select * from tb10;
 id | name ----+------
 1 | a
 2 | a
 3 | a
 4 | a
(4 rows)
postgres=# select currval('tb10_id_seq');
 currval ---------
 2
(1 row)

可以看到,表中id有值1,2,3,4,而序列的值还是2。
1,2,3,4是直接通过insert into tb10(id,name) select generate_series(1,4),'a';直接插入而没有使用默认的序列值,导致没有调用序列使之增长,所以序列一直是1.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读