Personal finance app database design

后端 未结 5 822
挽巷
挽巷 2020-12-13 15:47

After searching around for a minimalistic money tracking/budgeting app, I decided to build one for my own personal use.

However I\'m unsure with part of the database

5条回答
  •  悲&欢浪女
    2020-12-13 16:25

    If I were to design a minimalistic accounting application, I would probably do something like

    ledger
    -------------
       key          INT(12) PRIMARY KEY
       account_id   INT(10)
       category_id  INT(10)
       trans_type   CHAR(3)
       amount       NUMERIC(10,2)
    
    account
    ------------
       account_id   INT(10) PRIMARY KEY
       created      DATETIME
       name         VARCHAR(32)
       ...
    
    category
    ------------
       category_id  INT(10)
       name         VARCHAR(32)
       ...
    

    The column key would consist of a date and a zero-padded numeric value (i.e. 201102230000) where the last 4 digits would be the daily transaction id. This would be useful to track the transactions and return a range, etc. The daily transaction id 0000 could be the account balance at the beginning (or end) of the day, and the id 0001 and up are other transactions.

    The column trans_type would hold transaction codes, such as "DEB" (debit), "CRE" (credit), "TRA" (transfer) and "BAL" (balance), etc.

    With a setup like that, you can perform any kind a query, from getting all the "credit" transactions between any given date, to only the account balance at any given date, or date range.

    Example: fetch all credit and debit transactions between 2011-01-01 and 2011-02-23

    SELECT ledger.*, account.name, category.name
      FROM ledger
      JOIN account
        ON ledger.account_id = account.account_id
      JOIN category
        ON ledger.category_id = category.category_id
     WHERE (ledger.trans_type = "CRE"
         OR ledger.trans_type = "DEB")
       AND ledger.key BETWEEN 201101010000 AND 201102239999
     ORDER BY ledger.key ASC
    

    Example: fetch all transactions (except balances) between 2011-01-01 and 2011-02-23 for the account #1 (ex: Mortgage)

    SELECT ledger.*, account.name, category.name
      FROM ledger
      JOIN account
        ON ledger.account_id = account.account_id
      JOIN category
        ON ledger.category_id = category.category_id
     WHERE ledger.trans_type <> "BAL"
       AND ledger.key BETWEEN 201101010000 AND 201102239999
       AND account.id = 1
     ORDER BY ledger.key ASC
    

    So there you go, flexibility and extensibility.

提交回复
热议问题