1. 程式人生 > >PostgreSQL學習篇9.10 列舉型別

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,Mon,Tues,Wed,Thur,Fri,Sat}
(1 row)