首页 > 解决方案 > 为多个表创建外键约束

问题描述

我有一张桌子叫ProjectList. 我还有另外两个名为Estimatesand的表Orders

Estimates和的主键Orders 是中的外键ProjectList。首先创建记录ProjectList,然后Estimate创建记录,然后再创建Order记录。

我将如何在不违反的情况下创建ProjectList外键Estimates约束Orders命令外键约束?

我唯一能想到的就是在创建 Estimate 时创建一个空的 Orders 记录。不确定这是否是一个优雅的解决方案。

标签: sql-serverdatabase-design

解决方案


好吧,这里的根本问题是一个逻辑错误:您的数据库模型声称可以在项目存在之前进行项目估算和订单。
为了说明这一点,一个逻辑模型应该看起来像这样:

-- Project PRO exists.
--
project {PRO}
     PK {PRO}
-- Project estimate number EST_NO of project PRO exists.
--
estimate {PRO, EST_NO}
      PK {PRO, EST_NO}

      FK {PRO} REFERENCES project {PRO}
-- Project order number ORD_NO of project PRO exists.
--
order {PRO, ORD_NO}
   PK {PRO, ORD_NO}

   FK {PRO} REFERENCES project {PRO}

请注意您如何无法在项目之前创建估算或订单。如果出于某种原因您更喜欢单列 ID,则可以将示例修改为:

-- Project PRO_ID exists.
--
project {PRO_ID}
     PK {PRO_ID}

-- Project estimate identified by EST_ID
-- for project PRO_ID exists.
--
estimate {EST_ID, PRO_ID}
      PK {EST_ID}

      FK {PRO_ID} REFERENCES project {PRO_ID}

-- Project order identified by ORD_ID
-- for project PRO_ID exists.
--
order {ORD_ID, PRO_ID}
   PK {ORD_ID

   FK {PRO_ID} REFERENCES project {PRO_ID}

所以,FKs在你的例子中是相反的。数据库设计是关于逻辑的,它源于它。尽管您可能会找到一种方法来使用一些 SQL技巧来解决感知到的技术问题,但潜在的逻辑错误(错误)仍然存在。

笔记:

All attributes (columns) NOT NULL

PK = Primary Key
AK = Alternate Key (Unique)
FK = Foreign Key

推荐阅读