3

I have this query:

SELECT f.uid, fi.status FROM friends f
LEFT JOIN friends_invitations fi ON f.fid = fi.fid
WHERE (f.uid = 2 OR fi.uid = 2)

The above query is correct, however performance-wise it's scanning all rows in the friends table, and ignoring the f.uid index in the WHERE clause, despite fid and uid being indexes in BOTH tables.

Basically I want the optimal approach to retrieve a user that exists either in Friends or Friends Invitations table using the 'uid' field.

Any ideas/suggestions?

3 Answers 3

2

how about :

SELECT f.uid, fi.status 
FROM friends f 
LEFT JOIN friends_invitations fi ON f.fid = fi.fid 
WHERE (f.uid = 2) 
UNION
SELECT f.uid, fi.status 
FROM friends f 
INNER JOIN friends_invitations fi ON f.fid = fi.fid 
WHERE fi.uid = 2

The combination of the or and ther left join are making your query full scan

Sign up to request clarification or add additional context in comments.

1 Comment

Yep that's what I did, except for 'on fi.uid = 2' on the last line which I assume you meant 'WHERE fi.uid = 2'.
0

Use UNION:

SELECT f.uid FROM friends f WHERE f.uid = 2
UNION
SELECT f.uid FROM friends f
JOIN f.friends_invitations fi ON f.fid = fi.fid
WHERE fi.uid = 2

1 Comment

Thanks for the answer, but what if I want to retrieve fields from friends_invitations table as well, UNION sadly won't work as it looks for identical fields.
0
SELECT u.uuid, fi2.status FROM
( SELECT f.uid AS uuid FROM friends AS f WHERE f.uid = 2
  UNION
  SELECT fi.uid FROM friends_invitations AS fi WHERE fi.uid = 2 ) AS u
LEFT JOIN friends_invitations AS fi2 WHERE u.uuid = fi2.uid

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.