Checking for reciprocal relationships in mysql. A trivial one table problem.
Posted
by calumbrodie
on Stack Overflow
See other posts from Stack Overflow
or by calumbrodie
Published on 2010-06-02T09:45:58Z
Indexed on
2010/06/02
9:53 UTC
Read the original article
Hit count: 268
I have a mysql table that stores relationships. Items can be related to another item in one direction, or both items can be related to each other.
I want to return all items related to my primary item - but I also want to check to see if the related item has a 'reverse relationship' to the current item and show this as a boolean
|--------------|---------------|
| SKU | related_SKU |
|--------------|---------------|
| 0001 | 0099 |
| 0002 | 0099 |
| 0099 | 0001 |
|--------------|---------------|
If I want to get all relationships for SKU=0001
SELECT related_SKU from relationships where SKU='0001'
returns
|--------------|
| related_SKU |
|--------------|
| 0099 |
|--------------|
but what I want is
|--------------|---------------|
| related_SKU | reciprocal |
|--------------|---------------|
| 0099 | 1 |
|--------------|---------------|
or
SELECT related_SKU from relationships where SKU='0002'
|--------------|---------------|
| related_SKU | reciprocal |
|--------------|---------------|
| 0099 | 0 |
|--------------|---------------|
What's the best way to do this?
© Stack Overflow or respective owner