--方法一
create table test_a
(
id serial,
name character varying(128),
constraint pk_test_a_id primary key( id)
);
NOTICE: CREATE TABLE will create implicit sequence "test_a_id_seq" for serial column "test_a.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_test_a_id" for table "test_a"
CREATE TABLE
--方法二
create table test_b
(
id serial PRIMARY KEY,
name character varying(128)
);
NOTICE: CREATE TABLE will create implicit sequence "test_b_id_seq" for serial column "test_b.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_b_pkey" for table "test_b"
CREATE TABLE
--方法三
create table test_c
(
id integer PRIMARY KEY,
name character varying(128)
);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_c_pkey" for table "test_c"
CREATE TABLE
//方法三上面的一小段是工具生成的,如果表已经建好,只要用下面的语句即可生成自动增长序列
CREATE SEQUENCE test_c_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
alter table test_c alter column id set default nextval('test_c_id_seq');
很明显从上面可以看出,方法一和方法二只是写法不同,实质上主键都通过使用 serial 类型来实现的,
使用serial类型,PG会自动创建一个序列给主键用,当插入表数据时如果不指定ID,则ID会默认使用序列的
NEXT值。