数据库设计,用于多种产品的当前和历史定价

时间:2017-03-14 15:18:26

标签: database-design relational-database

以下是理想的设计?

目前的燃料价格 折扣价(不固定,与当前价格一起发布) 每种燃料的历史价格(用于绘图/历史查询)

我的想法是:

Product_table

  • product_id(pkey)
  • PRODUCT_NAME
  • product_brand

CURRENT_PRICE

  • PRODUCT_ID
  • site_price
  • discounted_price
  • CREATED_DATE

History_price

  • PRODUCT_ID
  • site_price
  • discounted_price
  • CREATED_DATE

通过网络抓取/解析数据源来填充数据。

Current_price& history_price看起来完全一样,是否应该将确定current_price的逻辑卸载到应用程序层?

1 个答案:

答案 0 :(得分:0)

你已经有了自己的设计。但不是两个价格表 - 只有一个。查看将在特定时间返回特定产品的数据和历史价格的查询结构:

select  p.ID, p.Name, p.Brand, pr.SitePrice, pr.DiscountedPrice
from    Products p
join    Prices   pr
    on  pr.ProductID = p.ID
    and pr.EffDate   =(
        select  Max( pr1.EffDate )
        from    Prices pr1
        where   pr1.ProductID = pr.ProductID
            and pr1.EffDate <= :DateOfInterest )
where   p.ID = :ProductOfInterest;

这将返回一行输出,其中包含产品信息(:ProductOfInterest)和在指定时间生效的价格信息(:DateOfInterest)。但是,如果将当前日期时间值放入:DateOfInterest,则会返回当前价格信息。

因此,您可以将所有价格(过去和现在)放在一个表格中,并使用相同的查询查询历史当前数据。实际上,删除where子句并将当前时间戳硬编码到视图中,现在您有一个只返回当前价格的数据源。

create view CurrentPrices as
select  p.ID, p.Name, p.Brand, pr.SitePrice, pr.DiscountedPrice
from    Products p
join    Prices   pr
    on  pr.ProductID = p.ID
    and pr.EffDate   =(
        select  Max( pr1.EffDate )
        from    Prices pr1
        where   pr1.ProductID = pr.ProductID
            and pr1.EffDate <= Now()
        );

现在,您对特定产品的当前价格信息的查询更简单:

select  *
from    CurrentPrices
where   ID = :ProductOfInterest;

目前,我们无法将参数传递到视图中,因此无法使用该视图及时回顾。但是当你看到你能得到什么时,这并不是一个特别大的劣势。但是,您可以创建一个匹配所有价格的视图来显示价格历史记录:

create view HistoricPrices as
select  p.ID, p.Name, p.Brand, hp.SitePrice, hp.DiscountedPrice, pr.EffDate
from    Products p
join    Prices   pr
    on  pr.ProductID = p.ID;

对于此查询,您当然希望公开生效日期。然后查询以获取产品的完整价格历史记录:

select  *
from    HistoricPrices
where   ID = :ProductOfInterest
order by EffDate;
相关问题