简体   繁体   English

两列的SQL唯一组合,反之亦然

[英]SQL unique combination of two columns and vice versa

I have the following table:我有下表:

ID
KEY_1
KEY_2

I want the combination of KEY_1 with KEY_2 to be unique and vice versa.我希望 KEY_1 与 KEY_2 的组合是唯一的,反之亦然。

ALTER TABLE dbo.table_name
  ADD CONSTRAINT uq_table_name UNIQUE(KEY_1, KEY_2);

This way I can make the combination between KEY_1 AND KEY_2 unique but I want the vice versa as well.这样我可以使 KEY_1 和 KEY_2 之间的组合独一无二,但我也希望反之亦然。

Example:例子:

KEY_1 = 111;
KEY_2 = 222;

I cannot insert this values again or neither can I insert the values vice versa.我不能再次插入这个值,或者我也不能插入这些值,反之亦然。

This shouldn't be valid (since it's the same pair of keys):这不应该是有效的(因为它是同一对密钥):

KEY_1 = 222;
KEY_2 = 111;

Thanks谢谢

You can achieve this with an unique functional index instead of an unique constraint.您可以使用唯一的功能索引而不是唯一的约束来实现这一点。

create unique index table_name_uix 
  on table_name (greatest(key_1, key_2), least(key_1, key_2));

Details on Postgres unique constraint vs unique index here Postgres 唯一约束与唯一索引的详细信息在这里

There is no simple way to do this.没有简单的方法可以做到这一点。

As you have discovered:正如你所发现的:

  • UNIQUE constraints are sets of attributes, not list of attributes. UNIQUE 约束是属性集,而不是属性列表。
  • UNIQUE only accepts attributes names UNIQUE 只接受属性名称

One way to solve this is by creating two new attributes: key1_key2 and key2_key1 (the concatenation of each attribute) and then adding these two attributes as UNIQUE constraints each.解决此问题的一种方法是创建两个新属性:key1_key2 和 key2_key1(每个属性的串联),然后将这两个属性分别添加为 UNIQUE 约束。

You could also have a trigger that would update these attributes automatically (during insert/update).您还可以有一个触发器来自动更新这些属性(在插入/更新期间)。 This way you would avoid consistency problems.这样你就可以避免一致性问题。

Another way to do it is by having a trigger that checks the constraint (sort of like a tuple constraint where you manually check the uniqueness of these concatenations (sounds more complicated and error prone than the UNIQUE solution).另一种方法是使用触发器来检查约束(有点像元组约束,您可以手动检查这些连接的唯一性(听起来比 UNIQUE 解决方案更复杂且更容易出错)。

You can add two columns to your table, key_min and key_max , use a trigger to calculate key_min = smallest value between key_1 and key_2 ;您可以在表中添加两列key_minkey_max ,使用触发器计算key_min = key_1key_2之间的key_2 key_max = largest value between key_1 and key_2 and create the constraint UNIQUE(key_min,key_max). key_max = key_1key_2之间的key_1并创建约束 UNIQUE(key_min,key_max)。 You can see a similar solution using MariaDB and virtual columns here .您可以在此处查看使用 MariaDB 和虚拟列的类似解决方案。

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

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