简体   繁体   中英

Database design best practice

Suppose a user is able to

(1) use money to buy something (Money leaves wallet)
(2) sell something to earn money (Money enters wallet) 

and I want to keep track of the transactions and ensure that they are accurate. And I have thought of two methods

(A) Keep track using three disjoint table

buys <userid, amount>
sells <userid, amount>
transaction <transactionid, userid, amount, type> 

i.e.
insert <u1, 90> into buys trigger insert <t1, u1, 90, 'buy'> 
for example

(B) Have buys and sells store transactionid from transaction table

buys <userid, transactionid> 
sells <userid, transactionid>
transaction <transactionid, amount> 

i.e.
insert <t1, 90> into transaction and insert <u1, t1> into buys

My questions will be what are the pros and cons to method (A) and (B) and what are the alternative methods/best practices out there?

You can do it like this:

  • user table: (userid, name, ...)
  • transaction table: (transactionid, amount, date, ...)
  • link user and transaction table, (transactionid, buyerid, sellerid). buyerid and sellerid are foreing keys of user.userid.

This way, you can get buyer and seller form one single query, and not two tables. If you need to keep track of offered price and paid price, they are just extra fields in the transaction table.

So any data on the transaction goes in the transaction table, any data related to the involded users goes into the link table.

I see entities (users, transactions) as separate tables, and actions as link tables between entities.

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.

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