sql-server - 为多个表创建外键约束
问题描述
我有一张桌子叫ProjectList
. 我还有另外两个名为Estimates
and的表Orders
。
Estimates
和的主键Orders
和 是中的外键ProjectList
。首先创建记录ProjectList
,然后Estimate
创建记录,然后再创建Order
记录。
我将如何在不违反的情况下创建ProjectList
外键Estimates
约束Orders
命令外键约束?
我唯一能想到的就是在创建 Estimate 时创建一个空的 Orders 记录。不确定这是否是一个优雅的解决方案。
解决方案
好吧,这里的根本问题是一个逻辑错误:您的数据库模型声称可以在项目存在之前进行项目估算和订单。
为了说明这一点,一个逻辑模型应该看起来像这样:
-- 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
推荐阅读
- php - 为什么 MongoDB 不能正确存储日期?
- python-3.x - pytest - 在构造函数中模拟构造函数
- delphi - 项目组中同名数据源的链接丢失
- git - 在 rebase 期间查看 git 中已删除文件的更改
- r - R:如何从下一行值中创建一个新的二进制列?
- python - Elasticsearch-py 索引需要 4 个参数,给定 5 个?
- tensorflow - 基于预训练模型训练 Mask R-CNN 的时间分配
- javascript - 如何打开页面并滚动到特定位置
- excel - 如何遍历列并将每列中的某些值存储到它们自己的变量中?
- c++ - 如何指定 bazel 的并行链接作业数量,与构建作业分开?