Database structure for storing historical data

后端 未结 7 986
夕颜
夕颜 2020-12-13 05:48

Preface: I was thinking the other day about a new database structure for a new application and realized that we needed a way to store historical data in an efficient way. I

7条回答
  •  青春惊慌失措
    2020-12-13 06:03

    When you are designing your data structures, be very carful to store the correct relationships, not something that is similar to the correct relationships. If the address for an order needs to be maintained, then that is because the address is part of the order, not the customer. Also, unit prices are part of the order, not the product, etc.

    Try an arrangement like this:

    Customer
    --------
    CustomerId (PK)
    Name
    AddressId (FK)
    PhoneNumber
    Email
    
    Order
    -----
    OrderId (PK)
    CustomerId (FK)
    ShippingAddressId (FK)
    BillingAddressId (FK)
    TotalAmount
    
    Address
    -------
    AddressId (PK)
    AddressLine1
    AddressLine2
    City
    Region
    Country
    PostalCode
    
    OrderLineItem
    -------------
    OrderId (PK) (FK)
    OrderItemSequence (PK)
    ProductId (FK)
    UnitPrice
    Quantity
    
    Product
    -------
    ProductId (PK)
    Price
    
    etc.
    

    If you truly need to store history for something, like tracking changes to an order over time, then you should do that with a log or audit table, not with your transaction tables.

提交回复
热议问题