是否可以定义一个外键,其字段属于不同但相关的表?

发布于 2024-12-12 20:47:34 字数 675 浏览 0 评论 0原文

给定四个表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

栀梦 2024-12-19 20:47:34

我认为(对我们和您而言)了解添加额外外键的目的很重要?

根据您尝试解决的具体问题(输入时的数据验证、级联删除等)以及解决这些问题的灵活性(能够或无法更改数据结构),您可以通过触发器实现逻辑约束。当我们只需要捕捉很少发生(如果有的话)的边缘条件时,我们有时会使用这种方法。

如果触发器不足以满足您的情况并且需要外键,那么您剩下的唯一选择(无需重新设计所有表)是将 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文