I have persons and a person can contact multiple other persons, so basically the “default” tables would be:
persons (id)
contacts (person1_id, person2_id)
With this schema, I’d have to issue queries like
SELECT *
FROM contacts c
WHERE ( person1_id = *id of person1* AND person2_id = *id of person2* )
OR
( person1_id = *id of person2* AND person2_id = *id of person1* )
to get the relation between two persons when I insert such a relation only once.
What is the common practice to deal with this situation?
- Insert data once and do such an OR query
- Insert the relation twice so that person1_id = id of person1 AND person2_id = id of person2 is enough
- An entirely different approach?
Assuming:
- The m:n table actually contains additional data, so if I create a relation for both ways, I’d have to duplicate the data
- This is a core part of the application and most non-trivial queries involve at least a sub query that determines whether or not such a relation exists
If you write your insert logic such that
person1_id < person2_idis true for all rows, then you can just write