在 postgresql 中创建一个自动递增的主键,使用自定义序列:
第 1 步,创建序列:
create sequence splog_adfarm_seq
start 1
increment 1
NO MAXVALUE
CACHE 1;
ALTER TABLE fact_stock_data_detail_seq
OWNER TO pgadmin;
第 2 步,创建表格
CREATE TABLE splog_adfarm
(
splog_key INT unique not null,
splog_value VARCHAR(100) not null
);
第 3 步,插入表格
insert into splog_adfarm values (
nextval('splog_adfarm_seq'),
'Is your family tree a directed acyclic graph?'
);
insert into splog_adfarm values (
nextval('splog_adfarm_seq'),
'Will the smart cookies catch the crumb? Find out now!'
);
第 4 步,观察行
el@defiant ~ $ psql -U pgadmin -d kurz_prod -c "select * from splog_adfarm"
splog_key | splog_value
----------+--------------------------------------------------------------------
1 | Is your family tree a directed acyclic graph?
2 | Will the smart cookies catch the crumb? Find out now!
(3 rows)
这两行的键从 1 开始并按序列定义递增 1。
Bonus Elite ProTip:
程序员讨厌打字,而且输入nextval('splog_adfarm_seq') 很烦人。您可以为该参数键入 DEFAULT,如下所示:
insert into splog_adfarm values (
DEFAULT,
'Sufficient intelligence to outwit a thimble.'
);
要使上述方法起作用,您必须在 splog_adfarm 表上为该键列定义一个默认值。哪个更漂亮。