How To Create A 'Two-Sided' Unique Index On Two Fields?

后端 未结 4 1033
醉话见心
醉话见心 2020-12-11 18:50

How can I efficiently create a unique index on two fields in a table like this: create table t (a integer, b integer);

where any unique combination of two different

4条回答
  •  Happy的楠姐
    2020-12-11 19:18

    How about controlling what goes into the table so that you always store the smallest number into the first column and the largest one in the second? As long as it 'means' the same thing of course. It's probably less expensive to do it before it even gets to the database.

    If this is impossible, you could save the fields as is but have them duplicated in numerical order into two OTHER fields, on which you would create the primary key (pseudo code-ish) :

    COLUMN A : 2
    COLUMN B : 1
    
    COLUMN A_PK : 1  ( if new.a < new.b then new.a else new.b )
    COLUMN B_PK : 2  ( if new.b > new.a then new.b else new.a )
    

    This could easily be done with a trigger (as in Ronald's response) or handled higher up, in the application.

提交回复
热议问题