枚举类型时包含一系列有序的静态值集合的一个数据类型,等于某些变成语言中的enum类型。
枚举类型的使用
与MySQL不一样,在PG中使用枚举类型需要先使用CREATE TYPE来创建此枚举类型。我们先列举个示例:
-- 建立一个名为week的枚举类型
CREATE TYPE week AS ENUM ('Sun', 'Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat');
--建表,插入数据
create table duty(persion text, day week);
insert into duty values('aa','Sun');
insert into duty values('bb','Mon');
-- 查询结果
postgres@postgres=# select * from duty;
persion | day
---------+-----
aa | Sun
bb | Mon
(2 rows)
postgres@postgres=# select * from duty where day='Sun';
persion | day
---------+-----
aa | Sun
(1 row)
--如果类型不对,会报错
postgres@postgres=# select * from duty where day='Suna';
ERROR: invalid input value for enum week: "Suna"
LINE 1: select * from duty where day='Suna';
定义好类型后,我怎么查看类型有没有创建或者查询有类型的具体定义呢?在psql中可通过\dT命令查看枚举类型的定义:
postgres@postgres=# \dT week
List of data types
Schema | Name | Description
--------+------+-------------
public | week |
(1 row)
postgres@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)
也可以直接查询系统表pg_enum查看枚举类型的定义:
postgres@postgres=# select * from pg_enum;
oid | enumtypid | enumsortorder | enumlabel
-------+-----------+---------------+-----------
20984 | 20983 | 1 | Sun
20986 | 20983 | 2 | Mon
20988 | 20983 | 3 | Tues
20990 | 20983 | 4 | Wed
20992 | 20983 | 5 | Thur
20994 | 20983 | 6 | Fri
20996 | 20983 | 7 | Sat
(7 rows)
枚举类型说明
在枚举类型中,值的顺序是创建枚举类型时定义的顺序,所有的比较运算符及相关的聚集函数都可以支持枚举类型。可以看下面的例子:
postgres@postgres=# select min(day),max(day) from duty;
min | max
-----+-----
Sun | Mon
(1 row)
postgres@postgres=# select enum_first(null::week), enum_last(null::week);
enum_first | enum_last
------------+-----------
Sun | Sat
(1 row)
最后修改时间:2024-07-23 16:46:52
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




