在mysql中建立一个朋友列表[英] setting up a friend list in mysql

本文是小编为大家收集整理的关于在mysql中建立一个朋友列表的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我想在我的在线游戏中列出朋友列表.我不确定如何设置它或从哪里开始.添加朋友并接受我可以处理的朋友部分,但我不知道如何在MySQL和PHP中进行设置.连接到每个用户的用户(朋友)列表?

推荐答案

如果您的友谊关系对称,则可以将每对存储在单独的记录中:

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

和查询所有B的朋友,这样的朋友:

SELECT  friend2
FROM    friends
WHERE   friend1 = 'B'

或在第一个字段中使用最小id存储用户,第二个字段中的用户最大的id在第二个字段中:

friend1  friend2
A        B
A        C
B        D

和查询B的朋友这样的朋友:

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

第一个选项在MySQL中更有效,这是您的友谊关系不对称的唯一选择(例如LiveJournal)

请参阅本文:

其他推荐答案

友谊实质上是两个人之间的相互关系.用数据库术语,这是两个用户之间的多对多关系.

因此,您需要的是一个链接表,该表将两个用户的引用列于ID.

示例

用户表

ID    Username
1     Bob
2     Jim
3     Alice

朋友表

user1    user2
1        2
2        3

这将使鲍勃朋友吉姆和吉姆与爱丽丝的朋友.

其他推荐答案

在Stackoverflow上的其他帖子中查看答案...一些简单但很棒的解释来完成您需要的东西.

facebook数据库设计?

本文地址:https://www.itbaoku.cn/post/597522.html

问题描述

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 set it up in mysql and php. A list of users (friends) connected to each user or something?

推荐答案

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:

其他推荐答案

A friendship is essentially a mutual relationship between two people. In database terms it's a many-to-many relationship between two users.

So what you need is a linking table that holds references to two users by ID.

Example

Users table

ID    Username
1     Bob
2     Jim
3     Alice

Friends table

user1    user2
1        2
2        3

This would make Bob friends Jim and Jim friends with Alice.

其他推荐答案

Check out the answers in this other post here on stackoverflow...some simple but great explanations to accomplishing what you need.

Facebook database design?