Checking for reciprocal relationships in mysql. A trivial one table problem.
- by calumbrodie
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?