PG枚举数据类型

来源:互联网 发布:艺术二维码生成器软件 编辑:程序博客网 时间:2024/05/26 02:22
highgo=# select * from pg_enum;
 enumtypid | enumsortorder | enumlabel 
-----------+---------------+-----------
(0 rows)
 
highgo=# select * from pg_enum1;
错误:  关系 "pg_enum1" 不存在
LINE 1: select * from pg_enum1;
                      ^
highgo=# create type week as enum ('sun','mon','tues');
CREATE TYPE
highgo=# select * from pg_enum;
 enumtypid | enumsortorder | enumlabel 
-----------+---------------+-----------
     16452 |             1 | sun
     16452 |             2 | mon
     16452 |             3 | tues
(3 rows)


highgo=# create type num1 as enum ('1','2','3');
CREATE TYPE
highgo=# select * from pg_enum;
 enumtypid | enumsortorder | enumlabel 
-----------+---------------+-----------
     16452 |             1 | sun
     16452 |             2 | mon
     16452 |             3 | tues
     16460 |             1 | 1
     16460 |             2 | 2
     16460 |             3 | 3
(6 rows)


highgo=# 


插入的数据需要在枚举类型之间,否则会报错:
highgo=# insert into dutty values ('1','sun');
INSERT 0 1
highgo=# insert into dutty values (1,'sun');
错误:  字段 "num" 的类型为 num1, 但表达式的类型为 integer
LINE 1: insert into dutty values (1,'sun');
                                  ^
HINT:  你需要重写或转换表达式


highgo=# insert into dutty values ('4','sun');
错误:  对于枚举num1的输入值无效: "4"
LINE 1: insert into dutty values ('4','sun');
                                  ^
 
highgo=# insert into dutty values ('2','fri');
错误:  对于枚举week的输入值无效: "fri"
LINE 1: insert into dutty values ('2','fri');
                                      ^
 
highgo=# select min(weekday) from dutty;
 min 
-----
 sun
(1 row)


highgo=# select max(weekday) from dutty;
 max 
-----
 sun
(1 row)


highgo=# select * from dutty where weekday=(select max(weekday) from dutty);
 num | weekday 
-----+---------
 1   | sun
(1 row)


返回枚举类型中的第一个和最后一个值:
highgo=# select enum_first(null::num1),enum_last(null::num1);
 enum_first | enum_last 
------------+-----------
 1          | 3
(1 row)
原创粉丝点击