第五章: 数组类型和组合类型
参考:《PostgreSQL 9.6.0 手册》
主要内容:创建-插入-访问-修改
一、数组类型
1. 创建数组
CREATE TABLE schools(
school_name text,
classes_name text[], --创建一维数组
students_info text[][] --创建二维数组
);
2. 插入数据
INSERT INTO schools (school_name,classes_name,students_info)
VALUES ('1st school',
'{"calss_1","class_2","class2"}',
'{{"class_1","zhangsan"},{"class_2","lisi"}}'
);
3. 访问数组
SELECT students_info[1][1],students_info[1][2] FROM schools
WHERE school_name='1st school';
4. 修改数组
UPDATE schools SET classes_name='{}';
二、组合类型
1. 创建组合类型
CREATE TYPE type_test AS( --注意不要漏了as
name text,
age integer,
sex text
);
CREATE TABLE table_test(
user_info type_test, --应用组合类型
pass_or_falue boolean
);
INSERT INTO table_test VALUES (ROW('zhangsan',20,'female'),true); --注意ROW()的使用
其实,只要你创建了一个表,也会自动创建一个组合类型来表示表的行类型,它具有和表一样的名称。
重要限制:因为没有约束与一个组合类型相关,显示在表定义中的约束不会应用于表外组合类型的值。
CREATE TABLE product(
product_id serial, --serial数据类型:自动生成序列
product_price real,
product_name text=
);
CREATE TABLE product_test(
product_info product, --未使用CREATE TYPE创建组合类型
Quality boolean
);
INSERT INTO product_test VALUES (ROW(1,1.2,'goo'),true);
2. 组合值输入(以下两种方法均可)
INSERT INTO product_test VALUES (ROW(1,1.2,'goo'),true);
INSERT INTO product_test VALUES ((1,1.2,'goo'),true);
INSERT INTO product_test VALUES ((,1.2,'goo'),true); --输入NULL,不填就好
INSERT INTO product_test VALUES ((,1.2,‘’),true); --输入空白字符串
3.访问组合类型中的域
为了和表中数据的访问方式进行区别,采用加圆括号的方式:
(product).product_id
4. 更新组合列
UPDATE table_test SET user_info =('wangwu',100,'male');
UPDATE table_test SET user_info =ROW('wangwu',100,'male');