PostgreSQL用自动增量更新主键

时间:2019-07-09 11:38:07

标签: postgresql insert unique primary-key

假设我们有下表:

drop table if exists modeling.pl_example_table;
create table modeling.pl_example_table (
    animal_name text,
    animal_id int
);

insert into modeling.pl_example_table (animal_name, animal_id) values 
('lion', 1),
('dog', null),
('cat', 2),
('catt', null);

我想创建一个助手表,该表将列出animal_name的所有可能值。 animal_name必须具有相应的animal_id。该信息将存储在下表中,我将使用具有非{animal_name NULL的{​​{1}}来初始化:

animal_id

drop table if exists modeling.pl_example_dictionary cascade; create table modeling.pl_example_dictionary as ( select animal_id as id, animal_name from modeling.pl_example_table where animal_id is not null); 不能为空pl_example_dictionary,并且animal_id必须是唯一的(例如,马不能同时拥有animal_name 1和151)。为了实现这一点,我使用以下约束:

animal_id

我不知道如何处理表中不能有两个主键的事实。序列不是从3开始而是从1开始存在问题(最好将该序列用alter table modeling.pl_example_dictionary add primary key(animal_name); alter table modeling.pl_example_dictionary add primary key(id); -- more than one PK is not allowed create sequence modeling.pl_example_dictionary_seq owned by modeling.pl_example_dictionary.id; alter table modeling.pl_example_dictionary alter column id set default nextval('modeling.pl_example_dictionary_seq'); 参数化。

0 个答案:

没有答案