I have multiple currencies (they are not real) and exchange rates between them. Eg currency_a , currency_b , 1.5 If i need to exchange A -> B i simply multiply value by 1.5 , or if i need to exchange B -> A i divide value by 1.5 . How can i properly express this in database?
You would simply have a conversion table with two columns as a conversion factor:
from_currency to_currency rate
A B 1.5
B A 0.66667
In this method, the rates are multiplicative and both pairs are stored. This should make it easy to use.
For performance, you want a primary key on (from_currency, to_currency)
.
That approach IS a M:M it's just that both sides reference the same parent table. The PK remains the same, but each should also be an FK. A sample layout maybe something like:
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)
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.