Followup: how to model discount on items in a database?

后端 未结 1 985
滥情空心
滥情空心 2021-02-04 19:15

I am building an ecommerce site and would like to offer discounts on certain items for a limited time. I would like to display how much discount we are offering per product. He

1条回答
  •  旧巷少年郎
    2021-02-04 19:45

    The design of the ProductPricing table allows us to never have to delete old pricing data (sometimes management wants a report based on that data). With what you have described above, you'd start like this (I changed the starting date just so it's easy to pick out that yes, this was the original price when the system went into place):

    ProductPricing
       1   |    Jan 1, 1970, 00:00:00 |   Jan 1, 2038, 00:00:00  |   10$ |   10$
    

    Now let's say you give a discount price on your apples, and you wanted to be proactive and set up the system for when the sale was over:

    ProductPricing
       1   |    Jan 1, 1970, 00:00:00 |  Dec 20, 2011, 00:00:00  |   10$ |   10$
       1   |   Dec 20, 2011, 00:00:01 |  Dec 26, 2011, 00:00:00  |  7.5$ |   10$
       1   |   Dec 26, 2011, 00:00:01 |   Jan 1, 2038, 00:00:00  |   10$ |   10$
    

    What we did here was:

    1. Update the existing record with the 2038 timestamp, changing the endDateTimeStamp field to reflect the beginning of the sale
    2. Insert a new record to define the sale
    3. Insert another new record to reflect the normal price again

    With no overlapping timestamps, you're guaranteed to get a single record when you query the database for your price. Thus,

    SELECT p.Name, pp.price, pp.original_price
    FROM Product p
    INNER JOIN ProductPricing pp ON pp.productId = p.productId
    WHERE NOW() BETWEEN pp.startDateTimeStamp AND pp.endDateTimeStamp
    

    would get you a product list with current pricing.

    0 讨论(0)
提交回复
热议问题