postgresql有个特有的功能,它就是表继承,这是它。下面来研究一下这个“特异功能”。
1. 建立父表和继承表:
create table employee
( id int not null,
employee_name varchar(64),
salary int check(salary>0),
primary key(id)
);
CREATE INDEX idx_employee_01 ON employee(employee_name);
create table employee_info
( depart_id int,
job_title varchar(64)
)inherits(employee);
查询继承表:
select * from employee_info;

可以看到id, emplyee_name, salary这3个字段给继承下来。
往employee_info表插入数据:
insert into employee_info
( id,
employee_name,
salary,
depart_id,
job_title
)values
(1,
'张三',
10000,
1001,
'IT manager'),
(2,
'李四',
20000,
1001,
'IT engineer')
;
再执行查询,结果如下:

可以看到,employee_info 完美地继承了父表employee的字段。
2. 查看父表和继承表的结构
父表:
dbsimple=# \d+ employee;

再看继承表:
dbsimple=# \d+ employee_info;

对比父表和继承表,可以看到主键和约束条件和索引没有被继承下来。
如果需要继承主键和约束条件,索引等,则需要在创建的时候加上Including all ;在建表的时候,发现多了"merging constraint"。
dbsimple=#drop table employee_info;
dbsimple=#create table employee_info
( &n

本文详细介绍了PostgreSQL数据库的表继承功能,包括如何创建和操作父表与继承表,如数据继承、结构继承、权限管理等方面,并探讨了多表继承、解除继承以及查询优化等高级用法。此外,还提到了继承与权限、表结构修改和数据操作之间的关系,展示了该特性在实际应用中的灵活性和复杂性。
最低0.47元/天 解锁文章
1554

被折叠的 条评论
为什么被折叠?



