私はテーブルFooを持っています
FOO
-------
id
name
BAR
-------
id
name
FOO_BAR_XREF
-------
foo_id
bar_id
foo.id の foo_bar_xref に bar_id が 1 のレコードがある FOO のすべてのインスタンスを選択し、foo.id に bar_id が 2 のレコード n foo_bar_xref があるレコードを foo から除外する必要があります。
foo -> foo_bar_xref は 1 対多です *強調されたテキスト*foo_bar_xref には foo_id ごとに複数の bar_id が含まれる場合があります
これは結合のみで可能ですか、それとも where 句で not exists ステートメントを使用する必要がありますか?
これまでのところ私は持っています
select f.name from FOO f
inner join FOO_BAR_XREF fb_1 on fb_1.foo_id = f.id
inner join FOO_BAR_XREF fb_2 on fb_2.foo_id = f.id
where fb_1.bar_id = 1 and fb_2.bar_id <> 2
group by f.name -- remove dupes - running on sql server and is paged with sql servers hackish over keyword where distinct doesn't work so well.
バーが 2 の foo を除外していない
これは機能しているようですが、最も効率的かどうかはわかりません
select f.name from FOO f
inner join FOO_BAR_XREF fb_1 on fb_1.foo_id = f.id and fb_1.bar_id = 1
left outer join FOO_BAR_XREF fb_2 on fb_2.foo_id = f.id and fb_2.bar_id = 2
where fb_2.bar_id is null
group by f.name -- remove dupes