繁体   English   中英

货币、汇率,如何建立适当的关系?

[英]Currencies, exchange rates, how to make proper relations?

我有多种货币(它们不是真实的)和它们之间的汇率。 例如currency_a , currency_b , 1.5如果我需要交换A -> B我只需将值乘以1.5 ,或者如果我需要交换B -> A我将值除以1.5 我怎样才能在数据库中正确表达这一点?

您只需有一个包含两列作为转换因子的转换表:

from_currency  to_currency    rate     
      A            B          1.5
      B            A          0.66667

在这种方法中,速率是相乘的,并且两对都被存储。 这应该使它易于使用。

为了提高性能,您需要(from_currency, to_currency)上的主键。

这种方法是 M:M 只是双方都引用同一个父表。 PK 保持不变,但每个都应该是 FK。 示例布局可能类似于:

create table currency ( 
             id_currency serial 
           , code        text
           , name        text
           , constraint  currency_pk
                         primary key (id_currency)
           , constraint  currency_bk 
                         unique (code)
           ) ; 
create table currency_conversion(
             from_currency integer 
           , to_currency   integer
           , rate          number(9,5)
           , constraint    currency_conversion_pk
                           primary key (from_currency,to_currency)
           , constraint    from_conversion_2_currency_fk
                           foreign key (from_currency)
                           references currency(id_currency)
           , constraint    to_conversion_2_currency_fk
                           foreign key (to_currency)
                           references currency(id_currency)
          );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM