Postgresql enforce unique two-way combination of columns

后端 未结 2 1657
离开以前
离开以前 2020-12-03 18:43

I\'m trying to create a table that would enforce a unique combination of two columns of the same type - in both directions. E.g. this would be illegal:

col1          


        
相关标签:
2条回答
  • 2020-12-03 19:00

    Do you consider the intarray extension to be magic?

    You'd need to use int keys for the users instead of text though...

    Here's a possible solution:

    create extension intarray;
    
    create table friendz (
      from_id int,
      to_id int
    );
    
    create unique index on friendz ( sort( array[from_id, to_id ] ) );
    
    insert into friendz values (1,2); -- good
    
    insert into friendz values (2,1); -- bad
    

    http://sqlfiddle.com/#!15/c84b7/1

    0 讨论(0)
  • 2020-12-03 19:18

    A variation on Neil's solution which doesn't need an extension is:

    create table friendz (
      from_id int,
      to_id int
    );
    
    create unique index ifriendz on friendz(greatest(from_id,to_id), least(from_id,to_id));
    

    Neil's solution lets you use an arbitrary number of columns though.

    We're both relying on using expressions to build the index which is documented https://www.postgresql.org/docs/current/indexes-expressional.html

    0 讨论(0)
提交回复
热议问题