电子书网站 自己做网站排名靠前
LightDB中可以如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 hengsheng(id int, employee person);
CREATE TABLE
postgres@postgres=# \d hengsheng Table "public.hengsheng"Column | Type | Collation | Nullable | Default
----------+---------+-----------+----------+---------id | integer | | | employee | person | | | -- 插入复合类型的数据
postgres@postgres=# insert into hengsheng values (1,'("amily",32)');
INSERT 0 1
postgres@postgres=# select * from hengsheng;id | employee
----+------------1 | (amily,32)
(1 row)postgres@postgres=# insert into hengsheng values(1, ROW('zhangpin',31));
INSERT 0 1
postgres@postgres=# select * from hengsheng;id | employee
----+---------------1 | (amily,32)1 | (zhangpin,31)
(2 rows)
-- ROW表达式插入
postgres@postgres=# insert into hengsheng values(2, ROW('zhangpin',31));
INSERT 0 1
postgres@postgres=# select * from hengsheng;id | employee
----+---------------1 | (amily,32)2 | (zhangpin,31)
(2 rows)
我们再看一下如何访问复合类型的数据:
--直接用类型名.字段名会报错
postgres@postgres=# select employee.name from hengsheng;
ERROR: missing FROM-clause entry for table "employee"
LINE 1: select employee.name from hengsheng;^
--加上圆括号类避免SQL解析器的混淆
postgres@postgres=# select (employee).name from hengsheng;name
----------amilyzhangpin
(2 rows)