表A (uid,bid) ,
uid代表:用户id
bid代表:uid关注的用户id
表数据示例:
uid bid
? ? ? ? ?1 2
? ? ? ? ?2 1
? ? ? ? ?1 3
------我的答案
select
t1.uid,
t1.bid
from tbl t1
join
(select
uid,bid
from tbl)t2
on t1.uid = t2.bid and t1.bid = t2.uid
实际上,一需要考虑到数据中的去重问题
chatgpt提供
distinct uid,bid
order by bid,uid
3.综合sql
SELECT DISTINCT t1.uid, t1.bid
FROM tab t1
JOIN tableA t2 ON t1.uid = t2.bid AND t1.bid = t2.uid
ORDER BY t1.uid, t1.bid;
select
uid,bid
from tbl
union
select
bid,uid
from tbl
select
uid,bid
from tbl
where (uid,bid) in ()t1
select
uid,bid,
count(*)
from t2
group by uid,bid
select
uid,bid
from tbl
having count(*) = 2
SELECT uid, bid
FROM tableA
WHERE (uid, bid) IN (
SELECT uid, bid
FROM tableA
UNION
SELECT bid, uid
FROM tableA
)
GROUP BY uid, bid
HAVING COUNT(*) = 2;
意外发现,使用group by 的时候,聚合可以直接在having后面完成,无需写在select这里。