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)
 

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...