我之前发过一个类似的问题,但这更具体。请看下面的图表:
这种设计的解释如下:
此处的目的是允许商店经理根据所需的商品创建订单“购物篮”,并允许创建的系统根据订单中包含的产品确定当时的最佳价格
因此,我设想ProductOrders
表最初保留productID
和关联的orderID
,同时保持bakerID
和pricingDate
的空(未确定)值,因为这将由系统确定和更新,然后构成最终订单。
既然你已经知道我想要做什么,请告诉我如何最好地建立这些关系。
谢谢!
答案 0 :(得分:2)
如果我理解正确,未定级的订单尚未分配面包师/定价(意味着当下订单时,尚未选择烘焙师烘烤产品)。
在这种情况下,订单可能针对Products Table,然后针对BakersProducts表进行“Finalized”。
解决方案可以是将ProductsOrders 2分开为“ProductID”,一个用于原始订购的ProductId(即Non Nullable) - 比如说ProductId,第二个是分配给BakersProducts的外键的一部分(比如ProductId2)。这意味着在ProductsOrders中,复合外键BakerId,ProductId2和PricingDate都可以为空,因为只有在订单完成后才会设置它们。
为了消除这种冗余,您可能还会考虑使用代理键而不是复合键。通过这种方式,BakersProducts将具有代理PK(例如BakersProductId),然后将其作为ProductsOrders中的可空FK引用。这也可以避免与ProductOrders中的Direct FK混淆到Product.ProductId(从上面看,它是原始产品系列作为订单的一部分)。
HTH?
编辑:
CREATE TABLE dbo.BakersProducts
(
BakerProductId int identity(1,1) not null, -- New Surrogate PK here
BakerId int not null,
ProductId int not null,
PricingDate datetime not null,
Price money not null,
StockLevel bigint not null,
CONSTRAINT PK_BakerProducts PRIMARY KEY(BakerProductId),
CONSTRAINT FK_BakerProductsProducts FOREIGN KEY(ProductId) REFERENCES dbo.Products(ProductId),
CONSTRAINT FK_BakerProductsBaker FOREIGN KEY(BakerId) REFERENCES dbo.Bakers(BakerId),
CONSTRAINT U_BakerProductsPrice UNIQUE(BakerId, ProductId, PricingDate) -- Unique Constraint mimicks the original PK for uniqueness ... could also use a unique index
)
CREATE TABLE dbo.ProductOrders
(
OrderId INT NOT NULL,
ProductId INT NOT NULL, -- This is the original Ordered Product set when order is created
BakerProductId INT NULL, -- This is nullable and gets set when Order is finalised with a baker
OrderQuantity BIGINT NOT NULL,
CONSTRAINT FK_ProductsOrdersBakersProducts FOREIGN KEY(BakersProductId) REFERENCES dbo.BakersProducts(BakerProductId)
.. Other Keys here
)