是否可以使用自定义订单索引创建ENUM类型。之后可以更新pg_type并将enumsortorder字段设置为所需值,但是问题是在创建过程中可以做吗?例如。像
CREATE TYPE environment AS ENUM ('stage' 10, 'prod' 20);
答案 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 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)
您还可以将函数使用的值存储在表中,以使修改变得更容易。