PostgreSQL 数据类型介绍(二)

  • Boolean 类型

Paste_Image.png

如图所示,常见的数据类型图片所示。

  • 枚举(enum)类型
    示例如下:

备注:其实和java里的枚举一样。

//创建一个枚举类型
postgres=# CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
CREATE TYPE
//创建 person 表,并使用该枚举。
postgres=# CREATE TABLE person (name text,current_mood mood);
CREATE TABLE
//插入一条记录:
postgres=# INSERT INTO person VALUES ('Moe', 'happy');
INSERT 0 1
//查询记录
postgres=# SELECT * FROM person WHERE current_mood = 'happy';
 name | current_mood 
------+--------------
 Moe  | happy
(1 row)


-- 输入一个不存在的枚举值, 将报错
postgres=# SELECT * FROM person WHERE current_mood = 'happ';
ERROR:  invalid input value for enum mood: "happ"
LINE 1: SELECT * FROM person WHERE current_mood = 'happ';
-- 避免报错的方法, 把枚举转换成text     
postgres=# SELECT * FROM person WHERE current_mood::text = 'happ';
 name | current_mood 
------+--------------
(0 rows)

postgres=# 
枚举值每一个在行中占用4 bytes :
postgres=# select current_mood,pg_column_size(current_mood) from person;
current_mood | pg_column_size
--------------+----------------
happy | 4
枚举的标签在定义中最大限制由NAMEDATALEN决定, 默认是64-1=63. 前面已经讲过. 意味着 枚举值不能超过 63个字符。
postgres=# \d pg_enum
    Table "pg_catalog.pg_enum"
    Column     | Type | Modifiers 
---------------+------+-----------
 enumtypid     | oid  | not null
 enumsortorder | real | not null
 enumlabel     | name | not null
//表名的长度也是NAMEDATALEN决定的。
postgres=# \d pg_class ;
         Table "pg_catalog.pg_class"
       Column        |   Type    | Modifiers 
---------------------+-----------+-----------
//表名也是一个name类型, 长度也不能超过63个字符。
 relname             | name      | not null
 relnamespace        | oid       | not null


查找枚举的数据结构 :
postgres=# select oid,typname from pg_type where typname='mood';
oid | typname
---------+---------
3952969 | mood
postgres=# select * from pg_enum where enumtypid=3952969;
enumtypid | enumsortorder | enumlabel
-----------+---------------+-----------
3952969 | 1 | sad
3952969 | 2 | ok
3952969 | 3 | happy

枚举类型变更(枚举类型的插入和删除)

ALTER TYPE name ADD VALUE new_enum_value [ { BEFORE | AFTER } existing_enum_value ]

This form adds a new value to an enum type. If the new value’s place in the enum’s ordering is not specified using BEFORE or AFTER, then the
new item is placed at the end of the list of values.

如果不指定 Before 和 AFTER 的话,默认插到最后。
一般尽量插到最后,否则会对性能有影响。
好比java里的集合吧,有序集合插到最后属组开销较小。

  • money类型
postgres=# show lc_monetary;
 lc_monetary 
-------------
 C
(1 row)

//将12.345换算成money
postgres=# select '12.345'::money;
 money  
--------
 $12.35
(1 row)

postgres=# show lc_monetary;
 lc_monetary 
-------------
 C
(1 row)

关于 monetary ,都是有固定格式的。
//重新设置参数 lc_monetary
postgres=# set lc_monetary='zh_CN';
SET
//将12.345换算成money
postgres=# select '12.345'::money;
  money  
---------
 ¥12.35
(1 row)

postgres=# 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值