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')     

输出结果如下:

enter image description here

解决方法

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