简体   繁体   中英

Best way to implement friends list into a database? MySQL

So my project has a "friends list" and in the MySQL database I have created a table:

nameA

nameB

Primary Key (nameA, nameB)

This will lead to a lot of entries, but to ensure that my database is normalised I'm not sure how else to achieve this?

My project also uses Redis.. I could store them there.

When a person joins the server, I would then have to search for all of the entries to see if their name is nameA or nameB, and then put those two names together as friends, this may also be inefficient.

Cheers.

The task is quite common. You want to store pairs where A|B has the same meaning as B|A. As a table has columns, one of the two will be stored in the first column and the other in the second, but who to store first and who second and why?

One solution is to always store the lesser ID first and the greater ID second:

userid1 | userid2
--------+--------
1       | 2
2       | 5
2       | 6
4       | 5

This has the advantage that you store each pair only once, as feels natural, but has the disadvantage that you must look up a person in both coumns and find their friend sometimes in the first and sometimes in the second column. That may make queries kind of clumsy.

Another method is to store the pairs redundantly (by using a trigger typically):

userid1 | userid2
--------+--------
1       | 2
2       | 1
2       | 5
2       | 6
4       | 5
5       | 2
5       | 4
6       | 2

Here querying is easier: Look the person up in one column and find their friends in the other. However, it looks kind of weird to have all pairs duplicated. And you rely on a trigger, which some people don't like.

A third method is to store numbered friendships:

friendship | user_id
-----------+--------
1          | 1
1          | 2
2          | 2
2          | 5
3          | 2
3          | 6
4          | 4
4          | 5

This gives both users in the pair equal value. But in order to find friends, you need to passes: find the friendships for a user, find the friends in these friendships. However, the design is very clear and even extensible, ie you could have friendships of three four or more users.

No method is really much better than the other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM