这几天学习了一下PostgreSQL数据库,从安装到简单的使用都平平淡淡,但是下面的这个功能还是给了我一点小惊喜。
表的继承
简单来说就是可以用继承的方法把一张表的列和数据传递给另一张表,子表可以比父表列多的一种结构。
下面用一个小例子来了解一下。
–创建父表并插入两条数据
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 1
–查看父表结构
mydb=# \d father_table
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.)
–查看子表结构
mydb=# \d child_table
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