I’m trying to set up a table that links two records from a different table. These links themselves need to be correlated to another table. So at the moment, my table looks like this:
link_id (primary key) item_id_1 (foreign key) item_id_2 (foreign key) link_type (metadata)
However, the links between items are not directional (i.e. it should make no difference whether an item is the first or second listed in a link). Ideally, I’d like for the item_id field to just appear twice; as it is I’ll have to be careful to always be checking for duplicates to make sure that there’s never a record created linking 12 to 14 if 14 to 12 already exists.
Is there an elegant database design solution to this, or should I just adopt a convention (e.g. id_1 is always the smaller id number) and police duplication within the application?
Thanks in advance!
Benzado already pointed it out – add a constraint that enforces that item_id_1 < item_id2:
So this will prevent the wrong data from being entered, rejecting such updates/inserts.
If you want to automatically correct it any situation where item_id_1 > item_id_2, you could add a trigger instead (technically you could have both, but then you might have some hassle getting it to work right, as check constraints could be checked before the trigger fires). Exact syntax for triggers depends on you RDBMS.