Friend of a friend in PHP/MySQL?

前端 未结 5 1291
醉话见心
醉话见心 2020-12-04 20:52

I have a social network similar to myspace/facebook. In my code you are either a person\'s friend or not a friend, so I show all actions from people you are friends with (in

5条回答
  •  没有蜡笔的小新
    2020-12-04 21:09

    The simple approach would be to do some kind of simple nested clause. So say you have a table with posts and the posters id, and a friends table, the first layer would be

    SELECT post FROM posts JOIN friends 
      on post.userid = friends.friend_id 
      WHERE friend.id = 1 (user ID)
    

    then to get a friends of friends

    SELECT post FROM posts JOIN
       (SELECT DISTINCT friends_2.friend_id FROM friends AS friends_1 
            JOIN friends as friends_2 
            on friends_1.friend_id = friends_2.id where friends_1.id = 1) 
    AS friends 
    wHERE post.userid = friends.friend_id AND mainid = 1 (user ID)
    

    You can repeat this nesting each time you want to add another layer of friend abstraction. The problem with this approach is that it would take a very long time to execute. For every time you add a layer of friend abstraction you are increasing the complexity by a power of n (where n is the number of rows in your table).

    It is more likely that they are saving the viewable friends in a table somewhere, so lets make a new tabled called friends_web

    user_id, friend_id, level
    

    when a user friends someone, it adds that new friend into friends_web at a level of 0(since that friend is no people away) then adds that friends friends at a level of 1 (since its 1 friend away). In order to keep the table integrity you would also want to add the inverted record. To clarify if A adds B as a friend and C is a friend of B, the following two records would get added to our new table

    A, C, 1
    C, A, 1
    

    since now A can see C and C can see A.

    now when we want a query we just do

     SELECT post FROM posts 
      JOIN friends_web ON post.user_id = friends_web.friend_id 
      WHERE friends_web.user_id = user_id AND friends_web.level < 2 (or however deep you want to look)
    

    by doing that you minimized your query complexity when doing post lookups while being able to look more then 1 layer deep into a friend web.

    Sorry for the long winded response.

提交回复
热议问题