[英]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 ) ( 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. 但是,从具有7500条记录的好友表中选择结果需要1.5秒。 Is there a way to solve this problem?
有办法解决这个问题吗? I am not an expert in sql.
我不是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: 使用
union
或union all
比使用on
子句中的or
或case
更好。
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)
. 我会推荐
friends(status, friend_two, friend_one)
和friends(status, friend_one, friend_two)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.