在外键上添加约束

问题描述 投票:0回答:1

我有一个超一流的推广,它有3个子类GiftCard,Offers和TodaysDeals。

Promotion(PromotionID,expiryDate)
GiftCard(GiftCardID,points)
where GiftCard.giftcardID references promotion
TodaysDeals(TodaysDealsID,Discount)
where TodaysDeals.TodaysDealsID references promotion
Offers(OffersID,Discount)
where offers.offersID references promotion

GiftCard促销与客户有关,而优惠与交易与产品有关。产品不能同时有要约和交易。我想将promotionID添加到“产品”表中,确保该表中没有与GiftCardID相对应的任何promotionID。这种方法是否可以在eerd中表示并转换为sql代码?

我曾考虑过在交易和产品之间建立一种关系,在报价和产品之间建立另一种关系,但这不能满足产品不能同时具有要约和交易的约束,因为两个ID都将被表示作为产品表中的外键。

sql sql-server foreign-keys constraints erd
1个回答
0
投票

您可以将PromoType添加到表中,使Promotion(PromotionID,PromoType)唯一,并从其他表中引用此唯一键。

Promotion(PromotionID, 
         PromoType check ('Deal','Offer', 'Gift'),
         expiryDate,
         UNIQUE(PromotionID,PromoType)
)

Product(
  PromoId,
  PromoType check ('Deal','Offer'),
  FK (PromoId,PromoType) ref Promotion(PromotionID,PromoType)
) 
© www.soinside.com 2019 - 2024. All rights reserved.