微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PostgreSQL学习篇9.10 枚举类型

PG中要使用枚举类型需要先使用create type创建一个枚举类型。

创建并使用枚举类型:
postgres=# create type week as enum ('Sun','Mon','Tues','Wed','Thur','Fri','Sat');
CREATE TYPE
postgres=# CREATE TABLE testmj(name varchar(100),day week);
CREATE TABLE
postgres=# insert into testmj values('lm','Sun');
INSERT 0 1
postgres=# select * from testmj;
 name | day
------+-----
 lm   | Sun
(1 row)

postgres=# insert into testmj values('lm','SuN');    --插入枚举类型以外的值报错
ERROR:  invalid input value for enum week: "SuN"
LINE 1: insert into testmj values('lm','SuN');
                                       ^

查看枚举类型:

postgres=# \dT
     List of data types
 Schema | Name | Description
--------+------+-------------
 public | week |
(1 row)

postgres=# \dT week
     List of data types
 Schema | Name | Description
--------+------+-------------
 public | week |
(1 row)

postgres=# \dT+ week
                                      List of data types
 Schema | Name | Internal name | Size | Elements |  Owner   | Access privileges | Description
--------+------+---------------+------+----------+----------+-------------------+-------------
 public | week | week          | 4    | Sun     +| postgres |                   |
        |      |               |      | Mon     +|          |                   |
        |      |               |      | Tues    +|          |                   |
        |      |               |      | Wed     +|          |                   |
        |      |               |      | Thur    +|          |                   |
        |      |               |      | Fri     +|          |                   |
        |      |               |      | Sat      |          |                   |
(1 row)

postgres=# select * from pg_enum;
 enumtypid | enumsortorder | enumlabel
-----------+---------------+-----------
     24588 |             1 | Sun
     24588 |             2 | Mon
     24588 |             3 | Tues
     24588 |             4 | Wed
     24588 |             5 | Thur
     24588 |             6 | Fri
     24588 |             7 | Sat
(7 rows)

postgres=#

相关函数:
enum_first
enum_last
enum_range

postgres=# select enum_first('Mon'::week);
 enum_first
------------
 Sun
(1 row)

postgres=# select enum_first('Sun'::week);
 enum_first
------------
 Sun
(1 row)

postgres=# select enum_last('Sun'::week);
 enum_last
-----------
 Sat
(1 row)

postgres=# select enum_range('Sun'::week);
           enum_range           
---------------------------------
 {Sun,Mon,Tues,Wed,Thur,Fri,Sat}
(1 row)

postgres=# select enum_range(null::week);
           enum_range           
---------------------------------
 {Sun,Sat}
(1 row)
 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐