是否可以定义一个外键,其字段属于不同但相关的表?
给定四个表:
CREATE TABLE LIST_A (
A INT,
PRIMARY KEY (A)
)
CREATE TABLE LIST_B (
A INT,
B INT,
PRIMARY KEY (A, B),
FOREIGN KEY (A) REFERENCES LIST_A (A)
)
CREATE TABLE LIST_C (
C INT,
A INT,
PRIMARY KEY (C),
FOREIGN KEY (A) REFERENCES LIST_A (A)
)
CREATE TABLE LIST_D (
C INT,
D INT,
B INT,
PRIMARY KEY (C, D),
FOREIGN KEY (C) REFERENCES LIST_C (C)
)
我想添加另一个约束:给定 LIST_D
中的一行,其主行是 (C0,D0)
,及其在 LIST_C< 中的父行/code>,其主键为
C0
,(LIST_C.A, LIST_D.B)
对必须引用 LIST_B (A, B)
。如何在 SQL Server 2008 R2 中实现此功能?
Given four tables:
CREATE TABLE LIST_A (
A INT,
PRIMARY KEY (A)
)
CREATE TABLE LIST_B (
A INT,
B INT,
PRIMARY KEY (A, B),
FOREIGN KEY (A) REFERENCES LIST_A (A)
)
CREATE TABLE LIST_C (
C INT,
A INT,
PRIMARY KEY (C),
FOREIGN KEY (A) REFERENCES LIST_A (A)
)
CREATE TABLE LIST_D (
C INT,
D INT,
B INT,
PRIMARY KEY (C, D),
FOREIGN KEY (C) REFERENCES LIST_C (C)
)
I want to add another constraint: Given a row in LIST_D
, whose primary is (C0,D0)
, and its parent row in LIST_C
, whose primary key is C0
, the pair (LIST_C.A, LIST_D.B)
must reference LIST_B (A, B)
. How do I implement this in SQL Server 2008 R2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为(对我们和您而言)了解添加额外外键的目的很重要?
根据您尝试解决的具体问题(输入时的数据验证、级联删除等)以及解决这些问题的灵活性(能够或无法更改数据结构),您可以通过触发器实现逻辑约束。当我们只需要捕捉很少发生(如果有的话)的边缘条件时,我们有时会使用这种方法。
如果触发器不足以满足您的情况并且需要外键,那么您剩下的唯一选择(无需重新设计所有表)是将 LIST_C.A 存储到 LIST_D 中,然后将 FKey 创建回 LIST_B。
另一种选择是重新设计它,以便您拥有包含所有表之间适当链接的中间表,但这听起来并不理想。
I think it is important (both for us and for you) to know the the purpose for adding the additional foreign key?
Depending on the exact problem you are trying to solve (data validation on entry, cascading deletes, etc) and the flexibility that you have for solving them (ability or inability to alter the data structure), you could implement logical constraints through triggers. We use this approach at times when we just need to catch edge conditions that should rarely, if ever, occur.
If triggers are insufficient for your situation and foreign keys are required, then about the only option that you have left (without redesigning all of the tables) is to store LIST_C.A into LIST_D and then create the FKey back to LIST_B.
The other option is to redesign it such that you have intermediate tables that contain the appropriate links between all of the tables, but it doesn't sound like this is desirable.