共同好友SQL with Join(Mysql)
我有两张桌子
用户表:
id|name
user_relationships
id | user_id | friend_id
并希望获得2个用户的共同朋友的名字。即:
user_relationships1 | 1 | 3
2 | 2 | 3
users
3| sammy
用户1和2有共同的朋友3。我想在一个查询中得到他的名字“ sammy”。
我怎么做?
回答:
SELECT id, nameFROM 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, nameFROM 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
以上是 共同好友SQL with Join(Mysql) 的全部内容, 来源链接: utcz.com/qa/425441.html