简体   繁体   中英

Managing Historical and Current Records with SQL

I want to keep track of each User 's current balance and balance history using the Django ORM. I imagine 2 tables ( User and History ) with a one-to-many between User and History representing a user's entire history, and a one-to-one between User and History for easy access to the current balance :

History    
ID | User (FK to User) | Delta | Balance | Timestamp

User    
ID | Name | Employee | Year | Balance (FK to History)

1) Does this seem reasonable given that I'm using the Django ORM? I think with raw SQL or another ORM, I could give history a start and stop date, then easily get the latest with SELECT * FROM History WHERE user_id=[id] AND stop IS NULL; .

2) Should History have a balance column?

3) Should User have a balance column (I could always compute the balance on the fly)? If so, should it be a "cached" decimal value? Or should it be a foreign key to the latest balance?

A strictly normal approach would say that neither table should contain a balance column, but that users' balances should be calculated when required from the sum of all their history. However, you may find that using such a schema would result in unacceptable performance—in which case cacheing the balance would be sensible:

  • if you're mostly interested in the current balance, then there's little reason to cache balances in the History table (just cache the current balance in the User table alone);

  • on the other hand, if you might be interested in arbitrary historical balances, then storing a historical balances in the History table would make sense (and then there'd be little point in also storing the current balance in the User table, since that could easily be discovered from the most recent History record).

But perhaps it's not worth worrying about cacheing right now? Have in mind the mantra " normalise until it hurts; denormalise until it works " as well as Knuth's famous maxim " premature optimisation is the root of all evil ".

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