实际上,我有 2 个表,朋友表和用户表我试图实现的是通过检查另一个用户的朋友来检索我共同的朋友,并从用户的表中获取这些共同朋友的数据
表友是这样构建的
id | user1 | user2 | friend_status
那么表数据如下所示
1 | 1 | 2 | 1
2 | 1 | 3 | 1
3 | 2 | 3 | 1
4 | 1 | 4 | 1
5 | 2 | 4 | 1
然后假设我是 id 为 2 的用户,那么在该表中,我有 3 个朋友 - 1、3 和 4。我要检索的是用户 1 的共同朋友,它们也有 3 个朋友 - 2、3 和 4,并从表用户中检索 2 个共同朋友 3 和 4 的数据
您可以使用UNION
让用户成为好友:
SELECT User2 UserId FROM friends WHERE User1 = 1
UNION
SELECT User1 UserId FROM friends WHERE User2 = 1
然后,在UserId
上加入两个不同用户的UNION
,您可以获得共同的朋友:
SELECT UserAFriends.UserId FROM
(
SELECT User2 UserId FROM friends WHERE User1 = 1
UNION
SELECT User1 UserId FROM friends WHERE User2 = 1
) AS UserAFriends
JOIN
(
SELECT User2 UserId FROM friends WHERE User1 = 2
UNION
SELECT User1 UserId FROM friends WHERE User2 = 2
) AS UserBFriends
ON UserAFriends.UserId = UserBFriends.UserId
这是一种使用 union all
组合用户 1 和用户 2 的所有好友并使用 count(distinct src) > 1
仅选择与两个用户都是好友的方法。
select friend from (
select 2 src, user1 friend from friends where user2 = 2
union all select 2, user2 from friends where user1 = 2
union all select 1, user1 from friends where user2 = 1
union all select 1, user2 from friends where user1 = 1
) t group by friend
having count(distinct src) > 1
你需要这样的东西吗?
create table #table (id int, user1 int , user2 int, friend_status int)
insert into #table values
(1 , 1 , 2 , 1),
(2 , 1 , 3 , 1),
(3 , 2 , 3 , 1),
(4 , 1 , 4 , 1),
(5 , 2 , 4 , 1),
(6 , 2 , 1 , 1),
(7, 3 , 7 , 1)
select *from #table
select t1.user1, t1.user2 as friend
from #table t1
inner join
#table t2
on (t1.user2 = t2.user2
and t1.user1 <> t2.user1)
where t1.user1<>2
order by t1.user1