1

ユーザーとフレンド テーブルを含むリレーショナル データベースで、フレンドである異性のユーザーのペアを特定しようとしています。したがって、ユーザー a は潜在的にユーザー b と友達になることができますが、その逆はできません。a が b と友達で、b も a と友達であるすべてのインスタンスを見つけたいと思います。一方向の友情をすべて異性に返すクエリがありますが、一致しないペアを取り出すために回答をさらに減らす方法がわかりません。

これはテーブルの構造です:

Table: users
Attributes: id, name, gender
Table: friends
Attributes: id1, id2, startdate
4

2 に答える 2

2

性別が常に M または F であると仮定して、すべての相互 MF 友情を見つけるには、次のようにします。

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;
于 2013-10-16T06:00:33.690 に答える
0

INTERSECTの代わりに使用しUNIONます。両方のサブクエリに存在するレコードが必要です。(おそらく s も必要ありませんDISTINCT。)

于 2013-10-16T06:00:57.463 に答える