Got a table of people, who I want to link to each other, many-to-many, with the links being bidirect

Posted by dflock on Stack Overflow See other posts from Stack Overflow or by dflock
Published on 2010-05-21T05:34:11Z Indexed on 2010/05/21 5:40 UTC
Read the original article Hit count: 349

Filed under:
|

Imagine you live in very simplified example land - and imagine that you've got a table of people in your MySQL database:

create table person (
    person_id int,
    name text
)

select * from person;

+-------------------------------+
|   person_id |            name |
+-------------------------------+
|           1 |           Alice |
|           2 |             Bob |
|           3 |           Carol |
+-------------------------------+

and these people need to collaborate/work together, so you've got a link table which links one person record to another:

create table person__person (
    person__person_id int,
    person_id int,
    other_person_id int
)

This setup means that links between people are uni-directional - i.e. Alice can link to Bob, without Bob linking to Alice and, even worse, Alice can link to Bob and Bob can link to Alice at the same time, in two separate link records. As these links represent working relationships, in the real world they're all two-way mutual relationships. The following are all possible in this setup:

select * from person__person;

+---------------------+-----------+--------------------+
|   person__person_id | person_id |    other_person_id |
+---------------------+-----------+--------------------+
|                   1 |         1 |                  2 |
|                   2 |         2 |                  1 |
|                   3 |         2 |                  2 |
|                   4 |         3 |                  1 |
+---------------------+-----------+--------------------+

For example, with person__person_id = 4 above, when you view Carol's (person_id = 3) profile, you should see a relationship with Alice (person_id = 1) and when you view Alice's profile, you should see a relationship with Carol, even though the link goes the other way.

I realize that I can do union and distinct queries and whatnot to present the relationships as mutual in the UI, but is there a better way? I've got a feeling that there is a better way, one where this issue would neatly melt away by setting up the database properly, but I can't see it. Anyone got a better idea?

© Stack Overflow or respective owner

Related posts about mysql

Related posts about many-to-many