PostgreSQL表继承(inherits)的使用

搬瓦工机场JMS

PostgreSQL 支持表继承,首先定义一个父表,然后使用关键字 INHERITS 定义一个子表,子表继承父表的所有字段定义。

定义一个父表:
create table parent(id int, name varchar(50));

定义一个子表,从 parent 表继承:
create table child(age int) inherits (parent);

插入数据:
insert into parent values(1, ‘a’);
insert into child values(2, ‘b’, 2);

查询父表、子表数据:

db=# select * from parent;
 id | name
----+------
  1 | a
  2 | b
(2 rows)
db=# select * from child;
 id | name | age
----+------+-----
  2 | b    |   2
(1 row)
db=# select * from only parent;
 id | name
----+------
  1 | a
(1 row)
  • 查询父表(parent)会将子表的数据也一起查出来。
  • 查询子表(child)则只有子表数据能被查出来。
  • 如果只想查父表数据,不包含子表数据,需要加 only 关键字,来限定只查父表数据。update, delete 同样支持 only 关键字。
    • update only parent set name = ‘c’;
    • delete from only child where name=’b’;

未经允许不得转载:搬瓦工VPS_美国VPS » PostgreSQL表继承(inherits)的使用

赞 (0) 打赏

相关推荐

    暂无内容!

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏