简体   繁体   English

SQL:如何对两个项目的组合(无序)唯一的两列应用唯一约束

[英]SQL: How to apply unique constrains to two columns where the combination of the two items (orderless) is unique

I have a table with three columns ( node1 varchar, node2 varchar, other_data int ) 我有一个包含三列的表( node1 varchar, node2 varchar, other_data int

node1 and node2 are nodes that make up an edge for a graph. node1和node2是组成图边的节点。

So if node1 = A and node2 = B , it would be equivalent for node1 = B and node2 = A . 因此, if node1 = A and node2 = B ,则等效于node1 = B and node2 = A

Is there a way to ensure duplicate entries could not be created. 有没有一种方法可以确保无法创建重复的条目。

For example, if the following is input: 例如,如果输入以下内容:

node1 = A, node2 = B, other = 123

If someone tried to input the following it would fail as the two nodes are already in the table: 如果有人尝试输入以下内容,则它将失败,因为表中已经有两个节点:

node1 = B, node2 = A, other = 123

编写一个触发器,以在node1和node2的SORTED组合上构建一个构造字段,然后尝试将其插入唯一索引中。

I would normally implement this with a CHECK constraint such that node1 always sorts earlier than node2 : 我通常使用CHECK约束来实现这一点,以使node1总是比node2早排序:

create table T(
  node1 varchar(20) not null,
  node2 varchar(20) not null,
  other_data int null,
  constraint CK_T_node_order CHECK (node1<node2),
  constraint UQ_T_nodes UNIQUE (node1,node2)
)

It adds a small amount of complexity to INSERT but makes enforcing your desired constraint quite easy. 它增加了复杂性, 少量 INSERT ,但使强制执行您想要的约束很容易。

Of course, you haven't said what SQL product your using. 当然,您还没有说您使用什么SQL产品。 If yours doesn't support CHECK constraints (Grr. MySQL, I'm looking at you), You'd have to use a trigger to implement the check constraint instead. 如果您的服务器不支持CHECK约束(MySQL,我正在查看您),则必须使用触发器来实现检查约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM