psql-04数据类型(2)

复合类型

  • PostgreSQL中可以如C语言中的结构体一样定义一个复合类型;
  • 创建
create type person as (
  name text,
  age int,
  sex boolean
);

create table author (
  id int,
  person_info person,
  book, text
);
  • 查询定义的复合类型和枚举类型一样

  • 输入

insert into author values (1, '("jinks", 24, true)', 'test book');

//用row表达式来构造复合类型值

insert into author values (1, row('jinks', 24, true), 'test book');

//只要表达式有超过一个字段,row关键字也可以省去

insert into author values (1, ('jinks", 24, true), 'test book');

  • 访问
select (person_info).name from author;
  • 更新
update author set person_info = row('pen' 24, true) where id = 1;
update author set person_info = ('pen' 24, true) where id = 1;

//只更新一个复合字段的某个子域;注意set后不要跟圆括号;

update author set person_info.name =  'jinks'  where id = 1;
update author set person_info.age = (person_info).age + 1 where id = 1;
  • 使用row表达式和使用引号还有一个区别就是使用引号时,对于在字符串类型中保存反斜杆,必须加两层;

XML类型

  • 用于储存xml数据,数据库会对输入的数据进行安全性检查;
  • 使用xml类型数据时注意字符集问题;

JSON类型

  • 同上,也会自动进行安全性检查;

  • PostgreSQL9.4中又提供了JSONBl类型

    • JSON类型把输入的数据不变地保存,使用时重新解析;
    • JSONB类型在存放时就把JSON解析成二进制格式,使用时性能更高;
    • JSONB支持在其上建索引;
  • 把一个JSON字符串转换成JSONB类型时, JSON字符串内的数据类型实际上被转换成PostgreSQL中的类型,映射关系如下:

JSON PostgreSQL 注意点
string text 注意字符集的一些限制
number numeric JSON中没有PostgreSQL中的NaN和infinity值
boolean boolean JSON仅能用小写true,false|
null (none) SQL中的NULL代表不同的意思

Range类型

数组类型

  • 定义:
//在目前PostgreSQL中,定义数组长度和纬度都是没有意义的

create table arr1(id int, col1 int[], col2 text[]);

create table arr2(id int, col1 int[10], col2 text[][]);
  • 输入
insert into arr1 values (1, '{1,2,3}', '{a,b,c}');

//除了`box`类型分隔符为分号外,其他都基本使用逗号;

create table arr2 (box box[]);
insert into arr2 values('{((0,1),(2,3));((1,1),(2,2))}');

//字符串内容允许空格但不许为空
//字符串有逗号输入要用双引号
//字符串有单引号输入用两个单引号
//字符串双引号输入要加反斜杠

//多维数组输入

insert into arr3 values (array[['a','b'],['c','d']]);
insert into arr3 values ('{{a,b},{c,d}}');
  • 访问
//一维数组

select col[1] form arr where id = 1;

//PostgreSQL中数组的下标默认从1开始;也可以插入数据的时候指定

create table test(id init[]);
insert into test values('[0:2]={1,2,3}');   //使用切片
select id[0], id[1], id[2] from test;
select id[0:2] from test;  

//二维数组必须使用切片
//访问多维数组的一维

select id[1][1] form test;
  • 修改
//注意不能修改多维数组中某一维的值

update test set col[1][2] = 2 where id = 1; 

伪类型

  • 不能作为字段的数据类型,但可以用于声明一个函数的参数或者结果类型;

UUID类型

  • 用于存储一个UUID;

pg_lsn类型

  • pg_lsn类型是PostgreSQL9.4版本之后提高的LSN的一种数据类型;LSN表示WAL日志的位置,在一些记录WAL日志信息的表系统中某些字段的类型就是pg_lsn类型;
原文地址:https://www.cnblogs.com/jinkspeng/p/5023569.html