简体   繁体   中英

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 )

表结构

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.

说明

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM