簡體   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