r/DatabaseHelp • • Feb 20 '18

Best way to store inventory +/- data?

Hi. I have an app where I am trying to store inventory numbers to be used for historical aggregation or to output to a chart over time. Right now, I am almost sure that I am not doing things optimally.

current:

ID (PK)TimestampDescriptionCat1Cat2Cat3
1232012-02-02September Shipment0195

When I add inventory, right now, I am logging it like the above, where I have numbers in category 1, category 2, category 3 to represent the numbers added. And when I want to aggregate data, I can just sum up numbers based on the dates selected. The main flaw is that if I add a category, I need to update the database to add a category column (Cat) and update my script to account for the new column.

other idea:

(NO PK)

TimestampDescriptionCategoryNumber
2012-02-02September ShipmentCat10
2012-02-02September ShipmentCat219
2012-02-02September ShipmentCat35

new idea (multi tables):

Shipment ID(PK)TimestampDescription
1232012-02-02September Shipment

(NO PK)

Shipment IDCategoryNumber
12310
123219
12335

Any thoughts? Other ideas? Is there a term to be used here that I should know in DB speak? TY!

2 Upvotes

5 comments sorted by

2

u/xiongchiamiov Feb 20 '18

Yes, that's a common pattern. It's known as a one-to-many relationship, and the shipment id is a foreign key.

1

u/rololoca Feb 20 '18

Thanks. I thought it looked better than the others. And that table using foreign keys has no PK, correct?

2

u/xiongchiamiov Feb 20 '18

I would suggest that every table should have an auto-incrementing primary key - eventually you'll find yourself wanting it, and if you have to add one that's a giant pain in the ass.

1

u/rololoca Feb 21 '18

Thanks. Probably a good idea. The additional size is probably worth the ability to sort the foreign key table.