我使用以下查询获取朋友关系:
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)
但是,从包含7500条记录的朋友表中选择结果需要1.5秒。有没有办法解决这个问题?我不是sql的专家。解释说明我正在做所有我认为导致麻烦的选择。
答案 0 :(得分:2)
使用union
或union all
比使用or
条款中的case
或on
更好:
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)
。