sql - PostgreSql中如何根据枚举类型获取枚举(使用条件语句)
问题描述
我在 Postgresql 中使用枚举。我在我的数据库中使用了一个名为 city 的枚举。我的要求是如何使用条件语句获取枚举。我使用了查询
SELECT 'Bengaluru'::CITY as TEXT
它工作正常,但如果在枚举中找不到文本,则会引发错误。我应该如何制作/更改 sql 查询,以便它不会引发错误。
解决方案
您需要为此检查系统表。假设一个枚举定义为:
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';
推荐阅读
- android - 如何在水平回收器视图中禁用片段滚动
- javascript - D3.js - 添加新节点并转换后旧链接不会被删除
- c - 置换和组合函数的内存存储
- php - 如何使用 Codeigniter 以 json 格式保存
- ios - WKWebView 加载后 6 秒显示警报
- linux - 意外回声
- flutter - Flutter:无法从 showModalBottomSheet 访问 Provider
- python - macOS 上的 PyQt5。添加到 QMainWindow 的自定义 QMenuBar 不可点击
- javascript - 问题让 localStorage 数据持久化
- reactjs - 在定义之前使用了“React”