如何在SQL中选择相互的Tinder匹配?

时间:2016-11-14 08:41:39

标签: sql

假设我们有一个名为matches的表(包含一些测试数据):

create table matches (
  user_id int,
  target_id int
);
INSERT INTO matches VALUES (1,2);
INSERT INTO matches VALUES (2,1);
INSERT INTO matches VALUES (3,5);
INSERT INTO matches VALUES (4,1);
INSERT INTO matches VALUES (1,4);
INSERT INTO matches VALUES (5,3);
INSERT INTO matches VALUES (5,4);
INSERT INTO matches VALUES (4,5);
INSERT INTO matches VALUES (1,3);
INSERT INTO matches VALUES (1,5);
INSERT INTO matches VALUES (6,1);
INSERT INTO matches VALUES (6,2);
INSERT INTO matches VALUES (6,3);
INSERT INTO matches VALUES (6,4);
INSERT INTO matches VALUES (6,5);
INSERT INTO matches VALUES (6,6); // me_irl

因此,对于此测试数据集,我们应该期望以下相互的Tinder匹配:

1,2
4,1
5,3
5,4

我如何在SQL中选择它?这是我得到的,它可以工作,但选择重复:

select A.user_id A, B.user_id B from
matches as A
inner join 
matches as B
on A.user_id = B.target_id
where A.user_id = B.target_id
and B.user_id = A.target_id

这是SQL查询返回的内容:

A   B
1   2
1   4
2   1
3   5
4   1
4   5
5   3
5   4

2 个答案:

答案 0 :(得分:2)

您可以通过添加“a.user_id< b.user_id”来过滤掉重复项。

像这样:

select A.user_id A, B.user_id B from
matches as A
inner join 
matches as B
on A.user_id = B.target_id
where A.user_id = B.target_id
and B.user_id = A.target_id
and a.user_id < b.user_id

答案 1 :(得分:1)

 select distinct case when A.user_id<B.user_id then A.user_id else B.user_id end as colum1,  case when A.user_id<B.user_id then B.user_id else A.user_id end as colum2 from
    matches as A
    inner join 
    matches as B
    on A.user_id = B.target_id
    where A.user_id = B.target_id
    and B.user_id = A.target_id

试试这个。我没有检查过。希望它有效