postgresql - PostgreSQL 中表的单独输入/输出类型
问题描述
我想知道是否可以通过 PostgreSQL 中的某个字典将列的输入设为一个字符串,而输出为不同的字符串。我确实知道如何使用 CASE 使用 SELECT 语句将数字转换为字符串,但是,我希望创建一个表,使得输入只需要数字,但输出总是给出字符串。
例如,对于货币 USD、CDN 和 GBP,其中 1 = USD、2 = CDN 和 3 = GBP,示例如下:
CREATE TABLE test_table (
currency CHAR (1) CHECK (currency IN ('1','2','3'))
)
我可以在哪里做到这一点:
INSERT INTO test_table (currency)
VALUES ('1')
INSERT INTO test_table (currency)
VALUES ('1')
INSERT INTO test_table (currency)
VALUES ('2')
INSERT INTO test_table (currency)
VALUES ('3')
INSERT INTO test_table (currency)
VALUES ('3')
输出如下所示:
解决方案
您可以使用 CASE 表达式:
select case currency
when '1' then 'USD'
when '2' then 'CDN'
when '3' then 'GBP'
when '4' then 'EUR'
end as currency
from test_table;
但更好的解决方案是创建一个货币表:
create table currency
(
id integer primary key,
currency_code varchar(3)
);
然后创建一个从基表到查找表的外键:
create table test_table
(
...
currency_id integer not null references currency,
...
);
然后使用连接显示代码:
select c.code
from test_table t
join currency c on c.id = t.currency_id;
推荐阅读
- vuejs2 - boostrap-vue 如何访问有序/过滤的行数据
- c++ - 关于在 cpp 中使用 const if inside 的 for 循环的最佳实践
- javascript - 有没有比添加 || 更好的解决方案 [ ] 到每个字段以在 ES6 中进行空检查
- javascript - 在打字稿中传递二维数组和空阴影数组?
- jquery - 单击时的 jQuery 不起作用,但“标准”单击事件可以
- anylogic - 使 3D 动画在透明 3D 折线内可见
- azure-ad-b2c - Azure B2C - 显示控制 - 使用 Mailjet 发送电子邮件验证
- mongodb - MongoDB,如何使用条件更新多个值
- ios - 为什么不可靠地调用 UIApplicationDelegate 方法`application(_:configurationForConnecting:options:)`
- php - 多态关系未在数据库中插入模型类型