一、PostgreSQL的自增id serial
1.2、serial的本質
我們在創建表時,經常需要使用到自增id,往往這麼寫,
create table test (
id serial, #使用serial來創建一個自增id
name varchar(64) not null
)
通過serial創建自增id,同時會創建屬於這個表的自增序列,並將id字段設置爲not null
serial和bigserial類型不是真正的類型,只是爲在表中設置唯一標識做的概念上的便利,本質上是創建了一個序列發生器,然後把自增字段的默認值設置爲這個序列發生器的nextval
CREATE TABLE tablename (
colname SERIAL
);
等價於
CREATE SEQUENCE tablename_colname_seq;
CREATE TABLE tablename(
colname integer DEFAULT nextval('tablename_colname_seq') NOT NULL
);
1.2、序列的屬性
postgres=# \d+ test5_id_seq
Sequence "public.test5_id_seq"
Column | Type | Value | Storage
---------------+---------+---------------------+---------
sequence_name | name | test5_id_seq | plain
last_value | bigint | 1 | plain
start_value | bigint | 1 | plain #序列起始值
increment_by | bigint | 1 | plain #每次遞增值
max_value | bigint | 9223372036854775807 | plain #最大值
min_value | bigint | 1 | plain #最小值
cache_value | bigint | 1 | plain
log_cnt | bigint | 0 | plain
is_cycled | boolean | f | plain #是否循環
is_called | boolean | f | plain
Owned by: public.test5.id
因爲自增本質上是取序列發生器的下一個值,所以可以多個表共用一個序列發生器,可以實現多表唯一值,當然,還可以設置序列是否可循環來實現id循環
例如:
二、序列
2.1創建序列
CREATE SEQUENCE name increment by 1 maxvalue 10 minvalue 1 start 1 cycle
2.2、序列操作
下一個值:nextval(regclass)
當前值:currval(regclass)
設置值:setval(regclass)
2.3、將序列綁定到表
create table test_seq (
id int not null default nextval('my_seq1'),
name varchar(64)
)