暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

PostgreSQL ---- 表的继承

原创 陈晓辉 2021-07-09
2196

这几天学习了一下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

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论