Inacio
Inacio

Reputation: 127

Mysql 5.7 slow CASE WHEN THEN query

I am fetching friend relationship using the following query:

SELECT F.friend_one, F.friend_two, F.requested_id, F.status
FROM users U, friends F
WHERE
CASE
WHEN F.friend_one = 2
THEN F.friend_two = U.id
WHEN F.friend_two= 2 
THEN F.friend_one= U.id
END
AND F.status = 1

(http://www.9lessons.info/2014/03/facebook-style-friend-request-system.html)

Table Structure

However, selecting results from friends table with 7500 records takes 1.5 seconds. Is there a way to solve this problem? I am not an expert in sql. The explain shows that I am doing ALL select which I think causing the trouble.

Explain

Upvotes: 1

Views: 662

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269953

You are probably better off with union or union all than in using or or case in the on clause:

SELECT F.friend_one, F.friend_two, F.requested_id, F.status
FROM users U JOIN
     friends F
     ON F.status = 1 AND F.friend_one = 2 AND F.friend_two = U.id
UNION ALL
SELECT F.friend_one, F.friend_two, F.requested_id, F.status
FROM users U JOIN
     friends F
     ON F.status = 1 AND F.friend_two = 2 AND F.friend_one= U.id;

You may also want to have indexes. I would recommend friends(status, friend_two, friend_one) and friends(status, friend_one, friend_two).

Upvotes: 2

Related Questions