FK 约束可以作用于多个表吗?
我有一个名为 Order
的表。它有一个名为 OrderSource
的表的 FK,该表有一个名为 SourceId 的非唯一 ID。 Order
还具有一个名为 OrderType
的表的 FK(可订购商品的目录)。它有一个 OrderTypeId 的 PK。
然后,我有另一个表 (Order_OrderSource
),它限制了给定 OrderTypeId 可以拥有的 SourceId 类型。 (它包含 OrderTypeId、SourceId 和 ClassId 行(另一个 Id,用于将特定源和 OrderType 分组在一起)。
我想要的是让数据库强制执行,如果 OrderTypeId 不匹配,则 Order 不能具有 OrderSource.SourceId这
是一种关联表模式,因为 SourceId 不是 OrderSource 的 PK
我可以通过任何方式让 SQL Server 强制执行 。这个约束?
I have a table called Order
. It has a FK to a Table called OrderSource
, which has a non-unique Id in called SourceId. Order
also has a FK to a table called OrderType
(a catalog of what can be ordered). It has a PK of OrderTypeId.
I then have another table (Order_OrderSource
) that limits the kinds of SourceIds I can have for a given OrderTypeId. (It contains rows of OrderTypeId, SourceId and ClassId (another Id that is used to group specific source and OrderTypes together).
What I would like is to have the database enforce that an Order cannot have a OrderSource.SourceId if it's OrderTypeId does not match up in the Order_OrderSource
table.
This is kind of an associative table pattern. But it breaks down because SourceId is not the PK of OrderSource.
Any way I can make SQL Server enforce this constraint?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来 Order_OrderSource 定义了 OrderType、OrderSource 和 Class 之间的有效关系?订单是按 OrderType、OrderSource 和(可能)类分类的吗?
如果是这样,为什么不在 Order_OrderSource 中定义有效组合,并在与该表相关的 Order 上创建一个 FK?那么您就不需要 Order 上的 SourceId 或 OrderTypeId,并且可以通过 FK 约束进行全面执行。
It sounds like Order_OrderSource defines valid relationships between OrderType, OrderSource, and Class? And Order is classified by OrderType, OrderSource and (maybe) class?
If that's the case, why not define the valid combinations in Order_OrderSource, and create an FK on Order that relates to this table? Then you have no need for SourceId or OrderTypeId on Order, and you have full enforcement via FK constraints.
是的,一列可以是不同表的多个外键约束的一部分。
外键需要您引用的列上有唯一索引(或主键)。在您的情况下,您可以使用
Order_OrderSource.(OrderSource,OrderType)
上的复合主键来满足此要求。SQL 示例:
(OrderSource, OrderType)
的组合现在受Order_OrderSource
中的行限制。Yes, one column can be part of multiple foreign key constraints to different tables.
A foreign key requires a unique index (or primary key) on the columns you are referencing. In your case, you could satisfy this requirement with a composite primary key on
Order_OrderSource.(OrderSource,OrderType)
.Example SQL:
The combination of
(OrderSource, OrderType)
is now limited by rows inOrder_OrderSource
.