首页 > 解决方案 > PostgreSql中如何根据枚举类型获取枚举(使用条件语句)

问题描述

我在 Postgresql 中使用枚举。我在我的数据库中使用了一个名为 city 的枚举。我的要求是如何使用条件语句获取枚举。我使用了查询

SELECT 'Bengaluru'::CITY as TEXT 

它工作正常,但如果在枚举中找不到文本,则会引发错误。我应该如何制作/更改 sql 查询,以便它不会引发错误。

标签: sqlpostgresqlenums

解决方案


您需要为此检查系统表。假设一个枚举定义为:

create type city as enum ('Munich', 'Berlin'); 

要确定是否为枚举类型定义了特定标签,可以使用以下命令:

select exists (select *
                from pg_enum e
                  join pg_type t on t.oid = e.enumtypid
                  join pg_namespace s on s.oid = t.typnamespace
                where s.nspname = 'public' --<< adjust here for the correct schema
                  and t.typname = 'city'
                  and e.enumlabel = 'Bengaluru');

正确的解决方案是不使用枚举,而是使用适当的一对多关系。

create table city
(
  id integer primary key, 
  name varchar(100) not null unique --<< the "unique" mimics the enuma
); 

insert into city (id, name)
values (1, 'Munich'), (2, 'Berlin');

要使用“枚举”,请使用外键:

create table some_table_using_city
(
   ... other columns ...
   city_id integer references city
);

要检查城市名称是否存在,只需使用:

select id
from city
where name = 'Bengaluru';

推荐阅读