I have a table called 'items' that looks something like this...
id | name
––––––––––––
1 | APPLES
2 | BANANAS
3 | ORANGES
4 | PEARS
... and a junction table called 'pairs', creating many-to-many relationships between the items...
id | item1_id | item2_id
––––––––––––––––––––––––
1 | 1 | 2
2 | 1 | 4
3 | 2 | 3
4 | 2 | 4
5 | 4 | 3
I have the following query to find items which are paired with a given item...
SELECT * FROM items i
WHERE
i.id IN (SELECT item1_id FROM pairs WHERE item2_id = 4)
OR
i.id IN (SELECT item2_id FROM pairs WHERE item1_id = 4)
Returning something like...
id | name
––––––––––––
1 | APPLES
3 | ORANGES
...which does the job, however, it runs pretty slowly (with a small test dataset of approximately 100 items, 1000 pairings it's already taking about 75ms).
My question is – can this be optimised further to speed it up (e.g. using joins rather than nested queries)?
Thanks for any help.