Get unique symmetric pairs from two columns with SQLite

不问归期 提交于 2021-01-24 07:44:25

问题


I have been looking at similar questions on Stack but any of them seems to be helpful to me. I have the following table called "Likes":

 ID1    ID2
1689    1709
1709    1689
1782    1709
1911    1247
1247    1468
1641    1468
1316    1304
1501    1934
1934    1501
1025    1101

I want to get the unique pairs between the two columns ID1 and ID2. That is:

 ID1    ID2
1689    1709
1501    1934

Any idea? Thx.


回答1:


It looks like you want pairs that exist in both versions, i.e. both as (x, y) and (y, x).

Can be done with a EXISTS query:

select t1.c1, t1.c2
from tablename t1
where t1.c1 < t1.c2
  and exists (select 1 from tablename t2
              where t1.c1 = t2.c2
                and t1.c2 = t2.c1)

Or as a JOIN:

select t1.c1, t1.c2
from tablename t1
join tablename t2
    on  t1.c1 = t2.c2
    and t1.c2 = t2.c1
where t1.c1 < t1.c2



回答2:


You can use the functions min and max to get the smallest and greatest of id1,id2 and look for symmetric pair combinations (a,b),(b,a) (count of a pair > 1). Then left join this on to the original table to get one such pair.

select l.*
from likes l
left join (select min(id1,id2) as minid,max(id1,id2) as maxid 
           from likes
           group by min(id1,id2),max(id1,id2)
           having count(*) > 1) t on t.minid=l.id1 and t.maxid=l.id2
where t.minid is null and t.maxid is null

Sample Demo

If you only need one pair when a symmetric pair exists, use

select min(id1,id2) as minid,max(id1,id2) as maxid 
from likes
group by min(id1,id2),max(id1,id2)
having count(*) > 1


来源:https://stackoverflow.com/questions/44001033/get-unique-symmetric-pairs-from-two-columns-with-sqlite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!