列出所有朋友并加入用户表
我有一个名为“friends”的数据库,它有“user_id”和“friend_id”列。 user_id 是邀请者,friend_id 是接收者。请注意,当创建友谊时,我不会在数据库中创建 2 条记录,例如 1,2 和 2,1。
考虑到我的 users.user_id 可能在“friends”表中的friends.friend_id 和friends.user_id 之间变化,如何列出我的所有朋友。还有如何将查询加入“用户”表以获取我所有朋友的姓名。
I have a database named 'friends' and it has columns 'user_id' and 'friend_id'.
user_id is the invitor and friend_id the recipient. Please note that when a friendship is created I'm NOT making 2 records in the database like 1,2 and 2,1.
How to list all the friends of mine, considering that my users.user_id can vary between friends.friend_id and friends.user_id in the 'friends' table. Also how to join the query to the 'users' table to get the names of all my friends.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种选择是两个查询的并集:
One option would be a union of two queries:
您应该进行加入查询以获得最佳性能。尝试这样的事情:
You should make a Join query to get the best performance. Try something like this:
我认为最简单的方法可能是确保friends
表的user_id
列中始终具有较低的 ID,而另一列中始终具有较高的 ID。这样,您就不需要检查两次,从而获得更好的性能。
但是,这种方法需要您修改添加好友的代码,并假设用户 ID 永远不会改变(或者您必须更新您的好友 ID)。表中的 ID)。
否则,请像 Joe 所说的那样使用
UNION
查询,或者使用OR
条件加入(例如JOIN ... ON u.user_id = Friends.user_id或 u.user_id = Friends.friend_id
) 或IN
(JOIN ... ON u.user_id IN (friends.user_id,friends.friend_id)
),这可能是昂贵的操作(使用EXPLAIN
和基准来找出答案)。I think it would probably be easiest to ensure that thefriends
table always has the lower ID in theuser_id
column and the higher one in the other.This way, you do not need to check twice, thus achieving better performance.
However, this approach requires you to modify your friend-adding code and assumes that user IDs never change (or you have to update your IDs in the table).
Otherwise, use
UNION
queries like Joe said or to join using anOR
condition (e.g.JOIN ... ON u.user_id = friends.user_id OR u.user_id = friends.friend_id
) orIN
(JOIN ... ON u.user_id IN (friends.user_id, friends.friend_id)
), which might be expensive operations (useEXPLAIN
and benchmarks to find out).