我之前发过类似的问题,但这个更具体。请看下图: 该设计的解释如下:
- 面包师生产多种产品
- 同一产品可以由多个面包师生产
- 面包师不时更改某些(他们的)产品的定价
- 可以创建订单,但不一定最终确定
这里的目的是允许商店经理根据需要的任何商品创建订单“篮子”,并允许正在创建的系统根据订单中包含的产品确定当时的最佳价格.
因此我设想了 ProductOrders
表最初持有 productID
和相关orderID
,同时为 bakerID
保留空值(未确定)和 pricingDate
,因为这将由系统确定和更新,然后构成最终订单。
既然您已经了解我正在尝试做什么,请告诉我如何最好地建立这些关系。
谢谢!
最佳答案
如果我没理解错的话,未完成的订单尚未指定面包师/定价(意思是在下订单时,尚未选择面包师来烘焙产品)。
在这种情况下,可能会根据 Products 表下订单,然后根据 BakersProducts 表“完成”订单。
一种解决方案可能是为 ProductsOrders 提供 2 个单独的“ProductID”,一个用于原始订购的 ProductId(即不可为空)- 例如 ProductId,第二个是分配给 BakersProducts 的外键的一部分(例如 ProductId2)。这意味着在 ProductsOrders 中,复合外键 BakerId、ProductId2 和 PricingDate 都可以为 null,因为只有在订单完成后才会设置它们。
为了消除这种冗余,您还可以考虑使用代理键而不是复合键。这样 BakersProducts 就会有一个代理 PK(例如 BakersProductId),然后在 ProductsOrders 中将其引用为可为 null 的 FK。这也可以避免与 ProductsOrders 中的直接 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
)
关于sql-server - 数据库设计-复合键关系问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4957683/