Closed. This question needs to be more focused。它目前不接受答案。
想改进这个问题吗?更新问题,使其只关注一个问题editing this post
5年前关闭。
在一个社交网络项目中,我希望随机获得朋友的朋友,以便向Facebook这样的用户提供建议。建议的用户数是动态的。但我们的表字段如下:
inviter_idfriend_idstatus
因此user id可以在inviter_idfriend_id中,status 2表示好友请求已被接受,并且他们目前是好友。
有人能帮我找个像样的解决办法吗?
我已经有了一个,这肯定会减慢网站,因为它越来越大,越来越重。
提前谢谢。

最佳答案

像这样的事情可能会发生。

SELECT DISTINCT id FROM (
    (SELECT t1.inviter_id as id FROM TableName t1 LEFT JOIN TableName t2 ON t1.friend_id = t2.inviter_id WHERE t1.status = 1 AND t2.status=1 AND t2.friend_id = UserId)
    UNION
    (SELECT t1.inviter_id as id FROM TableName t1 LEFT JOIN TableName t2 ON t1.friend_id = t2.friend_id WHERE t1.status = 1 AND t2.status=1 AND t2.inviter_id = UserId)
    UNION
    (SELECT t1.friend_id as id FROM TableName t1 LEFT JOIN TableName t2 ON t1.inviter_id = t2.inviter_id WHERE t1.status = 1 AND t2.status=1 AND t2.friend_id = UserId)
    UNION
    (SELECT t1.friend_id as id FROM TableName t1 LEFT JOIN TableName t2 ON t1.inviter_id = t2.friend_id WHERE t1.status = 1 AND t2.status=1 AND t2.inviter_id = UserId)
) as temp WHERE id != UserId AND NOT EXISTS (SELECT * FROM TableName WHERE (friend_id = id AND inviter_id=UserId) OR (inviter_id = id AND friend_id=UserId))

(用表名替换table name,用目标用户/变量替换UserId)。
链接到我的测试/示例:http://sqlfiddle.com/#!2/ddbec/2

关于php - 通过这种表结构,可以在PHP和MYSQL中成为 friend 的 friend 。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23994802/

10-11 12:08