假设我们有下表:
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');
参数化。