2 列组合上的 sql 唯一约束 [英] sql unique constraint on a 2 columns combination
本文介绍了2 列组合上的 sql 唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何为两列中的两个值的组合创建唯一约束.
How can you create a unique constraint on a combination of two values in two columns.
含义
column1 column2
2 1
寻找禁止的约束
column1 column2
1 2
推荐答案
如果您的数据库允许在索引中使用表达式,您可以执行以下操作 (ANSI SQL):
If your database allows expressions in an index you can do something like this (ANSI SQL):
CREATE UNIQUE INDEX on your_table (least(column1, column2)
, greatest(column1, column2));
请注意,这是唯一的索引,而不是唯一的约束.大多数 DBMS 的唯一区别是您不能将唯一索引作为外键的目标,否则它们的作用相同.
Note this is a unique index not a unique constraint. The only difference for most DBMS is that you can't have a unique index as the target of a foreign key, but otherwise they serve the same purpose.
如果您的 DBMS 没有 least()
或 greatest()
,您可以使用 CASE 表达式替换它们:
If your DBMS does not have least()
or greatest()
you can replace that using a CASE expression:
create unique index on your_table
(case column1 < column2 then column1 else column2 end,
case column2 > column1 then column2 else column1 end));
这篇关于2 列组合上的 sql 唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文