我在用mysql。有用户喜欢的桌子。然而,我一直在寻找喜欢彼此的人。
喜欢的桌子:
id (unique), from_user_id, to_user_id
1,3,1
2,1,3
3,1,64
4,1,2
5,2,1
例如,我想从用户id=1中找到相互喜欢的
因此,预期结果应为:
2,3
我试着用IN command连接两个列。
我尝试的SQL代码:
Select to_user_id from likes_table where from_user_id IN (Select from_user_id from likes_table where to_user_id = #id)
这只给出用户id=1
最佳答案
一种方法是针对两种情况筛选表:
行,其中from_user_id = 1
;和,
倒数行存在。
第二种情况可以使用exists
来处理:
select l.to_user_id
from likes l
where l.from_user_id = 1 and
exists (select 1
from likes l2
where l2.from_user_id = l.to_user_id,
l2.to_user_id = l.from_user_id
)