PostgreSQL:如何使用自定义emunsortorder值定义ENUM类型

时间:2018-12-13 14:27:35

标签: database postgresql enums

是否可以使用自定义订单索引创建ENUM类型。之后可以更新pg_type并将enumsortorder字段设置为所需值,但是问题是在创建过程中可以做吗?例如。像

CREATE TYPE environment AS ENUM ('stage' 10, 'prod' 20);

1 个答案:

答案 0 :(得分:2)

排序顺序由类型声明定义:

create type my_enum as enum ('first', 'third');

with t(v) as (
    values ('first'::my_enum), ('third')
)
select *
from t
order by 1;

   v   
-------
 first
 third
(2 rows)

您可以在所需位置添加新标签:

alter type my_enum add value 'second' before 'third';

with t(v) as (
    values ('first'::my_enum), ('third'), ('second')
)
select *
from t
order by 1;

   v    
--------
 first
 second
 third
(3 rows)    

了解CREATE TYPEALTER TYPE

如果以上条件还不够,请使用地图功能,例如:

create or replace function my_enum_map(my_enum)
returns int language sql as $$
    select case $1 
        when 'first' then 100
        when 'second' then 50
        when 'third' then 75
    end
$$;

with t(v) as (
    values ('first'::my_enum), ('third'), ('second')
)
select *
from t
order by my_enum_map(v);

   v    
--------
 second
 third
 first
(3 rows)

您还可以将函数使用的值存储在表中,以使修改变得更容易。