Postgresql enforce unique two-way combination of columns

后端 未结 2 1656
离开以前
离开以前 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

提交回复
热议问题