Postgresql 中文操作指南

9.10. Enum Support Functions #

对于枚举类型(在 Section 8.7 中介绍),有几个函数允许在不硬编码特定枚举值的计算情况下实现更简洁的编程。这些函数在 Table 9.35 中列出。示例假定创建一个枚举类型,如下所示:

For enum types (described in Section 8.7), there are several functions that allow cleaner programming without hard-coding particular values of an enum type. These are listed in Table 9.35. The examples assume an enum type created as:

CREATE TYPE rainbow AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'purple');

Table 9.35. Enum Support Functions

Function

Description

Example(s)

enum_first ( anyenum ) → anyenum

Returns the first value of the input enum type.

enum_first(null::rainbow)red

enum_last ( anyenum ) → anyenum

Returns the last value of the input enum type.

enum_last(null::rainbow)purple

enum_range ( anyenum ) → anyarray

Returns all values of the input enum type in an ordered array.

enum_range(null::rainbow){red,orange,yellow,​green,blue,purple}

enum_range ( anyenum, anyenum ) → anyarray

Returns the range between the two given enum values, as an ordered array. The values must be from the same enum type. If the first parameter is null, the result will start with the first value of the enum type. If the second parameter is null, the result will end with the last value of the enum type.

enum_range('orange'::rainbow, 'green'::rainbow){orange,yellow,green}

enum_range(NULL, 'green'::rainbow){red,orange,​yellow,green}

enum_range('orange'::rainbow, NULL){orange,yellow,green,​blue,purple}

请注意,除了 enum_range 的双参数形式外,这些函数都不考虑传递给它们的参数值;它们只关心声明的数据类型。可以传递 null 或该类型的具体值,结果相同。将这些函数应用于表列或函数参数,而不是像示例中那样应用于固定的类型名称更为常见。

Notice that except for the two-argument form of enum_range, these functions disregard the specific value passed to them; they care only about its declared data type. Either null or a specific value of the type can be passed, with the same result. It is more common to apply these functions to a table column or function argument than to a hardwired type name as used in the examples.