SQL

数据库设计集思广益:售价

发布于 2021-04-20 22:36:10

我需要创建一个数据库解决方案以提供产品折扣。

当前表:

Products
Columns: ProductId, ProductTypeId, ReleaseDate

ProductPrices
Columns: ProductPriceId, ProductPriceTypeId (one product may have n prices), ProductId, Price

我们希望能够按ProductId和/或ProductTypeId和/或ProductPriceTypeId和/或ReleaseDate打折。

销售示例:

  1. 折扣单个ProductId。
  2. 折扣指定ProductTypeId和ProductPriceTypeId的所有产品。
  3. 在上个月内使用ReleaseDate折扣指定ProductTypeId的所有产品。

#2具有挑战性的方面不是字面上的示例,而是在将来添加新字段的情况下考虑长期可伸缩性。

由于ReleaseDate,我很困惑如何处理#3。

下面是我意识到需要加入Stackoverflow之前在脑海中思考的问题。您会看到,由于明确包含了列,因此刚性结构将不允许良好的可伸缩性-
如果将来我们添加新条件,则需要将这些列添加到表中-更不用说它甚至不能处理ReleaseDate要求。

新表:

ProductPriceDiscounts
Columns: ProductPriceDiscountId, ProductPriceId, ProductTypeId, ProductPriceTypeId, Discount, DiscountTypeId (1 for percentage, 2 for fixed)

然后,我可以使用类似这样的方法来获取价格:

from p in Products
join pp in ProductPrices on p.ProductId equals pp.ProductId
let ppd = (
    from ppd in ProductPriceDiscounts
        .WhereIf(ppd.ProductPriceId != null, ppd.ProductPriceId == pp.ProductPriceId)
        .WhereIf(ppd.ProductTypeId != null, ppd.ProductTypeId == pp.ProductTypeId )
        .WhereIf(ppd.ProductPriceTypeId != null, ppd.ProductPriceTypeId == pp.ProductPriceId)
    select ppd).FirstOrDefault()
where p.ProductId = productId
select new 
{
    ...,
    Price = pp.Price,
    Discount = pp.Discount,
    DiscountedPrice = 
        (ppd.DiscountTypeId == 1) ? 
            (pp.Price - (pp.Price * pp.Discount)) :
            (pp.Price - pp.Discount) :
}

我仅提供了一个我想出的错误示例,以展示最终需要如何使用此新产品折扣功能的结果。任何人都可以提供建议来解决这种情况的好方法吗?谢谢。

关注者
0
被浏览
60
1 个回答
  • 面试哥
    面试哥 2021-04-20
    为面试而生,有面试问题,就找面试哥。

    我最终使用了原始设计,当我使用linq to sql查询数据库时,我使用一种方法获得了“
    DiscountedPrice”。该方法运行自己的查询并在返回结果之前对其执行条件逻辑。因此,这使我可以选择让我的代码执行我的查询无法执行的其他工作。我还为特殊的ProductPriceDiscountIds创建了一个Enum类,以便可以轻松识别它们。我希望这对发现自己处于类似情况的其他人有所帮助-
    到目前为止,对于我来说,它工作得很好。



推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看