对两个字段的唯一约束,以及它们的相反

Unique constraint on two fields, and their opposite(对两个字段的唯一约束,以及它们的相反)
本文介绍了对两个字段的唯一约束,以及它们的相反的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据结构,我必须在其中存储元素对.每对中正好有 2 个值,因此我们使用了一个表,其中包含字段 (leftvalue, rightvalue....).这些对应该是唯一的,如果键被更改,它们被认为是相同的.

I have a data structure, where I have to store pairs of elements. Each pair has exactly 2 values in it, so we are employing a table, with the fields(leftvalue, rightvalue....). These pairs should be unique, and they are considered the same, if the keys are changed.

Example: (Fruit, Apple) is the same as (Apple, Fruit).

如果可能以一种有效的方式,我会在字段上设置数据库约束,但不会以任何代价 - 性能更重要.

If it is possible in an efficient way, I would put a database constraint on the fields, but not at any cost - performance is more important.

我们目前使用的是 MSSQL server 2008,但可以更新.

We are using MSSQL server 2008 currently, but an update is possible.

有没有有效的方法来实现这一目标?

Is there an efficient way of achieving this?

推荐答案

两种解决方案,实际上都是将问题变得更简单.如果可以接受强制改变消费者,我通常更喜欢 T1 解决方案:

Two solutions, both really about changing the problem into an easier one. I'd usually prefer the T1 solution if forcing a change on consumers is acceptable:

create table dbo.T1 (
    Lft int not null,
    Rgt int not null,
    constraint CK_T1 CHECK (Lft < Rgt),
    constraint UQ_T1 UNIQUE (Lft,Rgt)
)
go
create table dbo.T2 (
    Lft int not null,
    Rgt int not null
)
go
create view dbo.T2_DRI
with schemabinding
as
    select
        CASE WHEN Lft<Rgt THEN Lft ELSE Rgt END as Lft,
        CASE WHEN Lft<Rgt THEN Rgt ELSE Lft END as Rgt
    from dbo.T2
go
create unique clustered index IX_T2_DRI on dbo.T2_DRI(Lft,Rgt)
go

在这两种情况下,T1T2 都不能在 Lft,Rgt 对中包含重复值.

In both cases, neither T1 nor T2 can contain duplicate values in the Lft,Rgt pairs.

这篇关于对两个字段的唯一约束,以及它们的相反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)