合 PG中的表继承和only关键词
官网:http://postgres.cn/docs/13/ddl-inherit.html
表继承简介
相似于程序语言的类继承,PostgreSQL的表也可以继承(Table Inheritance)。创建继承表的操作如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | CREATE TABLE cities ( name text, population real, altitude int -- (in ft) ); -- 创建继承的表 CREATE TABLE capitals ( state char(2) ) INHERITS (cities); postgres=# \d+ cities Table "public.cities" Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ------------+---------+-----------+----------+---------+----------+--------------+------------- name | text | | | | extended | | population | real | | | | plain | | altitude | integer | | | | plain | | Child tables: capitals Access method: heap postgres=# \d+ capitals Table "public.capitals" Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ------------+--------------+-----------+----------+---------+----------+--------------+------------- name | text | | | | extended | | population | real | | | | plain | | altitude | integer | | | | plain | | state | character(2) | | | | extended | | Inherits: cities Access method: heap |
这是先创建了cities表,然后创建了继承cities的capitals表。capitals的表中除了其特有的state列外,还含有和cities全部列相同的列。
因为表中没有内容所以看不出端倪,先插入数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | insert into cities values ('南通',500,4); insert into capitals values('南京',700,9,'js'); postgres=# select * from cities; name | population | altitude ------+------------+---------- 南通 | 500 | 4 南京 | 700 | 9 (2 rows) postgres=# select * from capitals; name | population | altitude | state ------+------------+----------+------- 南京 | 700 | 9 | js (1 row) postgres=# select * from only cities; name | population | altitude ------+------------+---------- 南通 | 500 | 4 (1 row) postgres=# select * from cities*; name | population | altitude ------+------------+---------- 南通 | 500 | 4 南京 | 700 | 9 (2 rows) |
第一个查询,是广义的,capitals继承了cities,所以capitals中的内容也会出现。
第二个查询,是查询capitals的。相当于单查黄狗。
需要注意2点:
1、如果只想查询父表的数据,那么需要在父表名称前加上only关键词。
2、对于UPDATE、DELETE和SELECT操作,如果在父表前不加only关键词,则会对父表和所有子表进行DML操作。所以,对于使用了继承表的场景,对父表的DELETE和UPDATE操作需要谨慎,因为会对父表和所有子表的数据进行DML操作。