[英]best way to store 1:1 user relationships in relational database
What is the best way to store user relationships, eg friendships, that must be bidirectional (you're my friend, thus I'm your friend) in a rel. 什么是存储用户关系的最佳方式,例如友谊,必须是双向的(你是我的朋友,因此我是你的朋友)。 database, eg MYSql? 数据库,例如MYSql?
I can think of two ways: 我可以想到两种方式:
Surely there is something better? 当然有更好的东西?
I would have a link table for friends, or whatever, with 2 columns both being PK's, and both being FK's to the User table. 我会有一个朋友或者其他的链接表,其中两列都是PK,而且两者都是用户表的FK。
Both columns would be the UID, and you would have two rows per friend relationship (A,B and B,A). 两列都是UID,每个朋友关系会有两行(A,B和B,A)。 As long as both columns are PK's, it should still be in normal format (although others are free to correct me on this) 只要两列都是PK,它应该仍然是正常格式(尽管其他人可以自由地纠正我)
Its a little more complex of a query, but nothing that can't be abstracted away by a stored procedure or some business logic, and its in Normal Format, which is usually nice to have. 它有点复杂的查询,但没有任何东西不能被存储过程或某些业务逻辑抽象出来,而且它是普通格式的,这通常很好。
You could check which of the two user_id's is the lowest and store them in a specific order. 您可以检查两个user_id中哪一个最低,并按特定顺序存储它们。 This way you don't need double rows for one friendship and still keep your queries simple. 这样,您不需要为一个友谊提供双行,并且仍然可以简化查询。
user_id_low | user_id_low | user_id_high user_id_high
a simple query to check if you're already friends with someone would be: 一个简单的查询来检查你是否已经是某人的朋友将是:
<?php
$my_id = 2999;
$friend_id = 500;
$lowest = min($my_id, $friend_id);
$highest= max($my_id, $friend_id);
query("SELECT * FROM friends WHERE user_id_low=$lowest AND user_id_high=$highest");
?>
Or you could find the lowest/higest userid using mysql 或者你可以使用mysql找到最低/最高的用户ID
<?php
query("SELECT * FROM friends WHERE user_id_low=LEAST($my_id, $friend_id) AND user_id_high=GREATEST($my_id, $friend_id)");
?>
And to get all your friends id's 并获得所有朋友的身份
<?php
query("SELECT IF(user_id_low=$my_id,user_id_high,user_id_low) AS friend_id FROM friends WHERE $my_id IN (user_id_low, user_id_high)");
?>
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. 我还记得在Twitter的自定义MySQL解决方案中看到信息,其中他们使用了一个额外的字段(朋友#,基本上)来进行自动限制和分页。 It seems pretty smooth: https://blog.twitter.com/2010/introducing-flockdb 看起来很顺利: https : //blog.twitter.com/2010/introducing-flockdb
使用键值存储,例如Cassandra。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.