如何在sql server中强制执行此约束

发布于 2024-08-29 21:45:34 字数 314 浏览 4 评论 0原文

我有一个名为 city 的表和一个名为 city_city 的表。 city_city 关联两个城市记录,因此它有一个 fromcity_id 和一个 tocity_id。我可以通过唯一键对 fromcity_id 和 tocity_id 强制执行唯一性,但是如何强制执行唯一性,以便在 fromcity_id 和 tocity_id 颠倒的情况下无法插入记录。

例如,以下记录在概念上是相同的:

id    fromcity_id  tocity_id
1     100          200
2     200          100

I have a table called city, and a table called city_city. city_city correlates two city records, so it has a fromcity_id and a tocity_id. I can enforce uniqueness on fromcity_id and and tocity_id through a unique key, but how do I enforce uniqueness so that I cant insert a record if fromcity_id and tocity_id are reversed.

For example, the following records are conceptually the same:

id    fromcity_id  tocity_id
1     100          200
2     200          100

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

蒲公英的约定 2024-09-05 21:46:10

添加强制执行 (fromcity_id < tocity_id) 的检查约束,然后就完成了

Add a check constraint that enforces (fromcity_id < tocity_id) and you are all set

起风了 2024-09-05 21:45:53

另一种选择是创建一个对视图具有唯一约束的索引视图(很糟糕,但也可以完成这项工作)。视图将类似于:

CREATE VIEW vwSomeView WITH SCHEMABINDING
AS
    SELECT fromcity_id AS 'C1', tocity_id AS 'C2' FROM city_city
    UNION ALL
    SELECT tocity_id AS 'C1', fromcity_id AS 'C2' FROM city_city

然后在视图上创建唯一索引:

CREATE UNIQUE INDEX UIX_vwSomeView ON vwSomeView (C1, C2)

问题是这与在每次插入时选择表的触发器相比是否具有更多、更少或大约相同的开销。答案是分析和测试您的工作负载、数据量和吞吐量。

Another option is to create an indexed view with a unique constraint on the view (horrid, but would also do the job). The view would be something like:

CREATE VIEW vwSomeView WITH SCHEMABINDING
AS
    SELECT fromcity_id AS 'C1', tocity_id AS 'C2' FROM city_city
    UNION ALL
    SELECT tocity_id AS 'C1', fromcity_id AS 'C2' FROM city_city

Then create a unique index on the view:

CREATE UNIQUE INDEX UIX_vwSomeView ON vwSomeView (C1, C2)

The question is whether this has more, less, or about the same overhead as a trigger that selects the table on each insert. The answer to this is to profile and test for your workload, data volumes and throughput.

溺深海 2024-09-05 21:45:48

这将需要一个触发器,因为您需要检查其他行。或者,您可以在应用程序层执行此操作。

This will require a trigger, because you need to examine other rows. Alernately, you could do this at the application layer.

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