PostgreSQL ---- 表的继承

这几天学习了一下PostgreSQL数据库,从安装到简单的使用都平平淡淡,可是下面的这个功能仍是给了我一点小惊喜。数据库

表的继承
简单来讲就是能够用继承的方法把一张表的列和数据传递给另外一张表,子表能够比父表列多的一种结构。学习

下面用一个小例子来了解一下。code

--建立父表并插入两条数据
mydb=# create table father_table(c1 integer,c2 varchar(10));
CREATE TABLE
mydb=# insert into father_table values(1,'101');
INSERT 0 1
mydb=# insert into father_table values(2,'201');
INSERT 0 1继承

--建立子表并插入两条数据
mydb=# create table child_table(c3 varchar(10)) inherits (father_table);
CREATE TABLE
mydb=# insert into child_table values(3,'301','302');
INSERT 0 1
mydb=# insert into child_table values(4,'401','402');
INSERT 0 1it

--查看父表结构
mydb=# \d father_tableio

Table "public.father_table"
Column Type Collation Nullable Default
c1 integer
c2 character varying(10)

Number of child tables: 1 (Use \d+ to list them.)table

--查看子表结构
mydb=# \d child_tableselect

Table "public.child_table"
Column Type Collation Nullable Default
c1 integer
c2 character varying(10)
c3 character varying(10)

Inherits: father_table方法

--检索父表全部记录
mydb=# select * from father_table;数据

c1 c2
1 101
2 201
3 301
4 401

(4 rows)

--检索父表全部记录
mydb=# select * from child_table;

c1 c2 c3
3 301 302
4 401 402

(2 rows)

--检索只属于父表的记录
mydb=# select * from only father_table;

c1 c2
1 101
2 201

(2 rows)

--检索只属于子表的记录
mydb=# select * from only child_table;

c1 c2 c3
3 301 302
4 401 402

(2 rows)

例子很简单,一看就明白了继承表的使用方法,我就不赘述了。

如今你们想一下ORACLE数据库怎么来实现上面的应用呢?
我在下一篇里分享给你们。

2021/06/17 @ Dalian

相关文章
相关标签/搜索