选择存在双向关系的两条记录

时间:2015-07-27 11:22:58

标签: sql

我有一个包含用户ID和名称的用户表。

我有一个包含UserID1和UserID2的Likes表。

当User1喜欢User2时,他们的ID分别输入到likes表中。

如何检索彼此相似的所有用户?

2 个答案:

答案 0 :(得分:2)

加入喜欢的表格并选择相互喜欢的行:

    select * 
      from Likes like1 
inner join Likes like2 on like1.UserID1 = like2.UserID2 
                      and like1.UserID2 = like2.UserID1

答案 1 :(得分:0)

使用自我加入

select t1.* from Likes as t1 
inner join Likes as t2  on t1.UserID1 = t2.UserID2 and t1.UserID2 = t2.UserID1