Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to store 1:1 user relationships in relational database

What is the best way to store user relationships, e.g. friendships, that must be bidirectional (you're my friend, thus I'm your friend) in a rel. database, e.g. MYSql?

I can think of two ways:

  1. Everytime a user friends another user, I'd add two rows to a database, row A consisting of the user id of the innitiating user followed by the UID of the accepting user in the next column. Row B would be the reverse.
  2. You'd only add one row, UID(initiating user) followed by UID(accepting user); and then just search through both columns when trying to figure out whether user 1 is a friend of user 2.

Surely there is something better?

like image 311
Aaron Yodaiken Avatar asked May 26 '10 01:05

Aaron Yodaiken


People also ask

How do you keep a one-to-one relationship in a database?

Primary Key as Foreign Key One way to implement a one-to-one relationship in a database is to use the same primary key in both tables. Rows with the same value in the primary key are related. In this example, France is a country with the id 1 and its capital city is in the table capital under id 1.

How do we store relationships in database?

A relational database collects different types of data sets that use tables, records, and columns. It is used to create a well-defined relationship between database tables so that relational databases can be easily stored. For example of relational databases such as Microsoft SQL Server, Oracle Database, MYSQL, etc.

What is the 1 1 relation in DBMS?

A One-to-One relationship is like a link between two tables of data in which each record occurs only once in each table. For example, employees and the automobiles they drive may have a One-to-One relationship.


1 Answers

Using double rows, while it creates extra data, will greatly simplify your queries and allow you to index smartly. I also remember seeing info on Twitter's custom MySQL solution wherein they used an additional field (friend #, basically) to do automatic limiting and paging. It seems pretty smooth: https://blog.twitter.com/2010/introducing-flockdb

like image 167
Joe Mastey Avatar answered Sep 17 '22 14:09

Joe Mastey