在具有用户和朋友表的关系数据库中,我试图确定异性用户是朋友。 因此,用户a可能与用户b成为朋友,但不是相反。我想找到所有的情况,其中a是朋友,b和b也是朋友。我有一个查询返回所有单向友谊到异性,但我不知道如何进一步减少取出非匹配对的答案。
这是表格的结构:
Table: users
Attributes: id, name, gender
Table: friends
Attributes: id1, id2, startdate
答案 0 :(得分:2)
要找到所有相互的M-F友谊,假设性别总是M或F:
select distinct a.name, a.id, b.name, b.id
from users a, users b, friends f1, friends f2
where f1.id1 = a.id
and f1.id2 = b.id
and a.gender != b.gender
and f2.id1 = b.id
and f2.id2 = a.id;
或者,使用ANSI连接语法:
select distinct a.name, a.id, b.name, b.id
from friends f1
join friends f2 on f1.id1 = f2.id2 and f1.id2 = f2.id1
join users a on a.id = f1.id1
join users b on b.id = f1.id2
where a.gender != b.gender;
答案 1 :(得分:0)
使用INTERSECT
代替UNION
。您需要两个子查询中存在的记录。 (你可能也不需要DISTINCT
。)