给定一个User表和Friend表,对于用户表中的每个用户,我想编写SQL查询来查找其朋友的共同朋友,即,对于User表中的UserID,查找彼此为朋友的现有朋友。例如
curl -H 'Accept-Encoding: br,gzip,deflate Host: cnpj.info Pragma: no-cache Cache-Control: no-cache Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 Upgrade-Insecure-Requests: 1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 --user-agent 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36' -X GET "http://cnpj.info/0101000"
我希望能够获得:
user_table
userID
1
2
5
friend_table
user1 user2
1 3
1 4
3 4
5 3
5 6
我尝试了类似的方法来获取用户ID和他们的朋友: (添加UNION只是为了消除由于双向关系而造成的重复)
user friend1 friend2
1 3 4
如何找到彼此是朋友的现有朋友?
答案 0 :(得分:0)
您可以只查看朋友,看看他们是否有您关心的普通朋友。假设关系是双向的:
with friends as (
select f.user
from friend_table ft
where ft.user1 = @user -- the original friend
)
select *
from friend_table ft join
friends f1
on ft.user1 = f1.user join
friends f2
on ft.user2 = f2.user
where ft.user1 < ft.user2 -- eliminate duplicates;