简体   繁体   中英

How do I design a database to store changes over time?

This database will store a list of children. But the problem is, they will have their weight measured once a day. How can I store the changes so I can easily query their actual weight and the weight variation over one day, one week and one month?

I'd think something like the following:

table kid
    int pkey(id)
    text name

table weight
    date when
    int kidid fkey(kid.id)
    int weight
    int pkey(id)

You need an one to many relationship between a 'child' table and a 'weight' table.

Child Table
-----------
ID (Generated) (PK)
Name 


WeightTable
-----------
ID (Generated) (PK)
Date
Weight
ChildID (FK)

It's late here, and I think I'm making it more complicated than I need to; and I'm reasonably sure you could just do a One-To-Many between Child and Weight. Every time you weigh the child, make a new entry.

You might also want to setup a few views (basically stored select operations) that show only the current weight, and or views for other common queries, thus isolating implementation from the users.

Now if this were me, and I had a huge amount of children to keep track of, I'd probably keep a cache table with results for frequent queries, but it's probably an overkill.

Two tables. The first, say children, should have an id column and information about each child like name, age, etc. The second should be called something like childrenweights. Each row contains three things. The id of the child from the children table, the weight, and the time the measurement was taken. Then you can use sql to query the children_weights table to select a range of weights for a child, say starting at January 1st and ending at January 8th and do whatever with them. Or you can even have the sql query return just the average or sum of that.

Child Table

ID (Generated) (PK)

text Name

float InitialWeight

WeightTable

ID (Generated) (PK)

date Date

float ChangeInWeight

ChildID (FK Child.ID)


Store only when ChangeInWeight <> 0.

Query Sum(ChangeInWeight) with date range from WeightTable relationship to find variation and Query IntitalWeight + Variation as above to Actualweight.

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