我有一个记录一些用户对的表。每行都表示两个用户是朋友。
用户_id1 | 用户_id2 |
---|---|
1 | 3 |
1 | 5 |
2 | 4 |
2 | 5 |
3 | 5 |
4 | 5 |
6 | 7 |
8 | 9 |
我想找到所有彼此是朋友且没有共同朋友的用户对并且我尝试过:
SELECT f1.user_id1, f1.user_id2
FROM Friends f1
LEFT JOIN Friends f2 ON (f1.user_id1 = f2.user_id1 AND f1.user_id2 <> f2.user_id2) OR (f1.user_id1 = f2.user_id2 AND f1.user_id2 <> f2.user_id1)
WHERE f2.user_id1 IS NULL AND f2.user_id2 IS NULL
ORDER BY f1.user_id1, f1.user_id2;
我得到了正确答案:
用户_id1 | 用户_id2 |
---|---|
6 | 7 |
8 | 9 |
但是当我向表中添加新行
(3,6)
时,我得到了错误的结果:
用户_id1 | 用户_id2 |
---|---|
8 | 9 |
此时正确的结果应该是:
用户_id1 | 用户 ID2 |
---|---|
3 | 6 |
6 | 7 |
8 | 9 |
有人能给我一个正确的方法吗?(顺便说一句,我使用PieCloudDB数据库)
我不知道pieclouddb是什么,但我认为以下查询适用于大多数RDBMS。(我在PostgreSQL中测试并得到了你期望的答案)
with a as (
select user_id1 u1, user_id2 u2 from friends
union all
select user_id2 u1, user_id1 u2 from friends
)
select user_id1,user_id2
from friends
where not exists(
(select u2 from a where u1 = user_id1)
intersect
(select u2 from a where u1 = user_id2)
)
order by user_id1,user_id2;