Mysql 5.7慢CASE WHEN那么查询

时间:2017-05-04 11:26:32

标签: mysql sql

我使用以下查询获取朋友关系:

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

但是,从包含7500条记录的朋友表中选择结果需要1.5秒。有没有办法解决这个问题?我不是sql的专家。解释说明我正在做所有我认为导致麻烦的选择。

Explain

1 个答案:

答案 0 :(得分:2)

使用unionunion all比使用or条款中的caseon更好:

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;

您可能还想拥有索引。我建议friends(status, friend_two, friend_one)friends(status, friend_one, friend_two)