setting up a friend list in mysql

前端 未结 4 1779
天涯浪人
天涯浪人 2021-01-31 12:47

I want to make a friends list in my online game. I am not sure how to set it up or where to start. The add friends and accept friends part I can handle, but I don\'t know how to

4条回答
  •  清歌不尽
    2021-01-31 13:39

    If your friendship relationship is symmetrical, you can either store each pair in a separate record:

    friend1 friend2
    A       B
    B       A
    A       C
    B       D
    C       B
    D       B
    

    and query all B's friends like that:

    SELECT  friend2
    FROM    friends
    WHERE   friend1 = 'B'
    

    or store the user with the least id in the first field and that with the greatest id in the second one:

    friend1  friend2
    A        B
    A        C
    B        D
    

    and query B's friends like that:

    SELECT  friend1
    FROM    friends
    WHERE   friend2 = 'B'
    UNION ALL
    SELECT  friend2
    FROM    friends
    WHERE   friend1 = 'B'
    

    The first option is a little bit more efficient in MySQL, and this is the only option if your friendship relationship is not symmetrical (like on LiveJournal)

    See this article:

    • Selecting friends

提交回复
热议问题