sql unique constraint on a 2 columns combination

谁都会走 提交于 2019-11-26 17:09:52

问题


How can you create a unique constraint on a combination of two values in two columns.

meaning

column1  column2 
   2        1 

looking for the constraint to disallow

column1  column2 
   1        2 

回答1:


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));

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.

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:


Looking at the documentation, found this for the ORACLE SGBD :

CREATE TABLE b(
 b1 INT, 
 b2 INT, 
 CONSTRAINT bu1 UNIQUE (b1, b2) 
                USING INDEX (create unique index bi on b(b1, b2)),
 CONSTRAINT bu2 UNIQUE (b2, b1) USING INDEX bi);

Chapter "Specifying the Index Associated with a Constraint" on the page ORACLE documentation.

Hop this help.




回答3:


A unique constraint on 2 columns only prevents those exact 2 values being inserted (switching them is allowed):

So you need A TRIGGER like this (ORACLE):

 CREATE TRIGGER trig1
        BEFORE INSERT ON TAB
        REFERENCING NEW AS NEW
        FOR EACH ROW
    DECLARE
        FOUND NUMBER;
    BEGIN
        SELECT COUNT(1) into FOUND FROM TAB WHERE
        (COLUMN1=:NEW.column2 AND COLUMN2=:NEW.column1) 
         OR (COLUMN1=:NEW.column1 AND COLUMN2=:NEW.column2); 
    IF FOUND>0 THEN
    raise_application_error (-20001,'INSERT not allowed');
    END IF;
        END trig1;

Warning: syntax not checked.



来源:https://stackoverflow.com/questions/10159411/sql-unique-constraint-on-a-2-columns-combination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!