PG中可以如C语言中的结构体定义一样定义一个复合类型。之所以支持复合类型,也是方便数据库应用程序开发的需要。可用CREATE TYPE语法创建复合类型,示例如下:
postgres@postgres=# create type person as (name text, age int);
CREATE TYPE
-- 创建成功person复合类型后,可用通过查系统表pg_type查看到该复合类型的信息。
postgres@postgres=# select * from pg_type where typname = 'person';
-[ RECORD 1 ]--+------------
oid | 39300
typname | person
typnamespace | 2200
typowner | 10
typlen | -1
typbyval | f
typtype | c
typcategory | C
typispreferred | f
typisdefined | t
typdelim | ,
typrelid | 39298
typelem | 0
typarray | 39299
typinput | record_in
typoutput | record_out
typreceive | record_recv
typsend | record_send
typmodin | -
typmodout | -
typanalyze | -
typalign | d
typstorage | x
typnotnull | f
typbasetype | 0
typtypmod | -1
typndims | 0
typcollation | 0
typaccess | n
typdefaultbin |
typdefault |
typacl |
创建好新的复合类型后,我们创建一个表,看一下如何插入复合类型的数据。除了采用’(var1, var2, …)'的方式表示复合类型常量,还可以采用ROW表达式语法来构造复合类型值。在大多数场合下,这种方法比用字符串文本的语法更简单,不用操心多重引号转义导致的问题。
postgres@postgres=# create table sheng(id int, employee person);
CREATE TABLE
postgres@postgres=# \d sheng
Table "public.sheng"
Column | Type | Collation | Nullable | Default
----------+---------+-----------+----------+---------
id | integer | | |
employee | person | | |
-- 插入复合类型的数据
postgres@postgres=# insert into sheng values (1,'("amily",32)');
INSERT 0 1
postgres@postgres=# select * from sheng;
id | employee
----+------------
1 | (amily,32)
(1 row)
postgres@postgres=# insert into sheng values(1, ROW('zhangpin',31));
INSERT 0 1
postgres@postgres=# select * from sheng;
id | employee
----+---------------
1 | (amily,32)
1 | (zhangpin,31)
(2 rows)
-- ROW表达式插入
postgres@postgres=# insert into sheng values(2, ROW('zhangpin',31));
INSERT 0 1
postgres@postgres=# select * from sheng;
id | employee
----+---------------
1 | (amily,32)
2 | (zhangpin,31)
(2 rows)
我们再看一下如何访问复合类型的数据:
--直接用类型名.字段名会报错
postgres@postgres=# select employee.name from sheng;
ERROR: missing FROM-clause entry for table "employee"
LINE 1: select employee.name from sheng;
^
--加上圆括号类避免SQL解析器的混淆
postgres@postgres=# select (employee).name from sheng;
name
----------
amily
zhangpin
(2 rows)
最后修改时间:2023-11-02 22:30:35
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




