首页 > 解决方案 > 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')     

输出如下所示:

在此处输入图像描述

标签: postgresqlsubstitution

解决方案


您可以使用 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;

推荐阅读