枚举(enum)类型是由一个静态、值的有序集合构成的数据类型。它们等效于很多编程语言所支持的enum
类型。枚举类型的一个例子可以是一周中的日期,或者一个数据的状态值集合。
枚举类型可以使用CREATE TYPE命令创建,例如:
CREATE TYPE mood AS ENUM ("sad", "ok", "happy");
一旦被创建,枚举类型可以像很多其他类型一样在表和函数定义中使用:
CREATE TYPE mood AS ENUM ("sad", "ok", "happy");
CREATE TABLE person (
name text,
current_mood mood
);
INSERT INTO person VALUES ("Moe", "happy");
SELECT * FROM person WHERE current_mood = "happy";
name | current_mood
------+--------------
Moe | happy
(1 row)
一个枚举类型的值的排序是该类型被创建时所列出的值的顺序。枚举类型的所有标准的比较操作符以及相关聚集函数都被支持。例如:
INSERT INTO person VALUES ("Larry", "sad");
INSERT INTO person VALUES ("Curly", "ok");
SELECT * FROM person WHERE current_mood > "sad";
name | current_mood
-------+--------------
Moe | happy
Curly | ok
(2 rows)
SELECT * FROM person WHERE current_mood > "sad" ORDER BY current_mood;
name | current_mood
-------+--------------
Curly | ok
Moe | happy
(2 rows)
SELECT name
FROM person
WHERE current_mood = (SELECT MIN(current_mood) FROM person);
name
-------
Larry
(1 row)
每一种枚举数据类型都是独立的并且不能和其他枚举类型相比较。看这样一个例子:
CREATE TYPE happiness AS ENUM ("happy", "very happy", "ecstatic");
CREATE TABLE holidays (
num_weeks integer,
happiness happiness
);
INSERT INTO holidays(num_weeks,happiness) VALUES (4, "happy");
INSERT INTO holidays(num_weeks,happiness) VALUES (6, "very happy");
INSERT INTO holidays(num_weeks,happiness) VALUES (8, "ecstatic");
INSERT INTO holidays(num_weeks,happiness) VALUES (2, "sad");
ERROR: invalid input value for enum happiness: "sad"
SELECT person.name, holidays.num_weeks FROM person, holidays
WHERE person.current_mood = holidays.happiness;
ERROR: operator does not exist: mood = happiness
如果你确实需要做这样的事情,你可以写一个自定义的操作符或者在查询中加上显式造型:
SELECT person.name, holidays.num_weeks FROM person, holidays
WHERE person.current_mood::text = holidays.happiness::text;
name | num_weeks
------+-----------
Moe | 4
(1 row)
枚举标签是大小写敏感的,因此"happy"
与"HAPPY"
是不同的。标签中的空格也是有意义的。
尽管枚举类型的主要目的是用于值的静态集合,但也有方法在现有枚举类型中增加新值和重命名值(见ALTER TYPE)。不能从枚举类型中去除现有的值,也不能更改这些值的排序顺序,如果要那样做可以删除并且重建枚举类型。
一个枚举值在磁盘上占据4个字节。一个枚举值的文本标签的长度受限于NAMEDATALEN
设置,该设置被编译在PostgreSQL中,在标准编译下它表示最多63字节。
从内部枚举值到文本标签的翻译被保存在系统目录pg_enum
中。可以直接查询该目录。
GRANT — 定义访问特权 大纲GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | TRIGGER }[, ...] | ALL [...
PREPARE — 为执行准备一个语句 大纲PREPARE name [ ( data_type [, ...] ) ] AS statement 描述 PREPARE创建一个预备语句。预备...
ROLLBACK — 中止当前事务大纲ROLLBACK [ WORK | TRANSACTION ] [ AND [ NO ] CHAIN ]描述 ROLLBACK回滚当前事务并且导致 该事务...
SET CONSTRAINTS — 为当前事务设置约束检查时机大纲SET CONSTRAINTS { ALL | name [, ...] } { DEFERRED | IMMEDIATE }描述 SET...
dropuser — 移除一个PostgreSQL用户账户大纲dropuser [connection-option...] [option...] [username]描述 dropuser移除一个已...