[英]mysql query help to find mutual friends on social networking site
I have a database table called users with a primary key of user_id for each user. 我有一个名为用户的数据库表,每个用户的主键为user_id。
I also have a table called friends with two fields, user_id and friend_user_id. 我还有一个名为friends的表,其中有两个字段user_id和friend_user_id。
The user_id field is always the lowest of the two user_id's in order to avoid duplicate entries. user_id字段始终是两个user_id中的最低者,以避免重复输入。
Say I have two users in mind, (lets say user id 1 and user id 4 although they could be anything). 假设我有两个用户,(尽管可以是用户ID 1和用户ID 4,但可以这样说)。
How would I return all rows from the users table for users that are friends with user 1 and user 4 (ie mutual friends)? 对于用户1和4的朋友(即共同的朋友),我如何从用户表中返回所有行?
I will give you the recipe: 我会给你食谱:
Much like this: 很像这样:
UPDATE: Here's the query: 更新:这是查询:
select f.friend_user_id from friends f where f.friend_user_id in (
select friend_user_id from friends where user_id=<id_of_user_a>)
and f.user_id=<id_of_user_b>
The ids returned by above query will be the id of all the users that are mutual friends of user_a and user_b. 上述查询返回的ID将是与user_a和user_b成为共同朋友的所有用户的ID。 If you want to get all the details (name, etc) about those users, then do this:
如果要获取有关这些用户的所有详细信息(名称等),请执行以下操作:
select f.friend_user_id,u.* from friends f inner join users u
on u.user_id=f.friend_user_id
where f.friend_user_id in (
select friend_user_id from friends where user_id=<id_of_user_a>)
and f.user_id=<id_of_user_b>
SELECT friends.friend_user_id FROM user, friends
INNER JOIN friends ON friends.user_id = user.user_id
WHERE user.user_id = 1
AND friend.friend_user_id
IN (SELECT friends.friend_user_id
FROM user, friends
INNER JOIN friends ON friends.user_id = user.user_id
WHERE user_id = 4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.