一尘不染

共同好友SQL with Join(Mysql)

mysql

我有两张桌子

用户表:

id|name

user_relationships

id | user_id | friend_id

并希望获得2个用户的共同朋友的名字。即:

user_relationships
1 | 1 | 3
2 | 2 | 3

users
3| sammy

用户1和2有共同的朋友3。我想在一个查询中得到他的名字“ sammy”。

我怎么做?


阅读 682

收藏
2020-05-17

共1个答案

一尘不染

SELECT id, name
FROM users
WHERE id IN (
  SELECT friend_id
  FROM user_relationships
  WHERE user_id IN ( 1, 2 )
  GROUP BY friend_id
  HAVING COUNT(friend_id) >= 2
)

或一次连接:

SELECT friend_id, name
FROM user_relationships r
  INNER JOIN users u ON r.friend_id = u.id
WHERE user_id IN ( 1, 2 )
GROUP BY friend_id
HAVING COUNT(friend_id) >= 2
2020-05-17