【发布时间】:2013-02-16 02:34:01
【问题描述】:
我有一张桌子 Foo
FOO
-------
id
name
BAR
-------
id
name
FOO_BAR_XREF
-------
foo_id
bar_id
我需要选择 foo.id 在 foo_bar_xref 中有一条 bar_id 为 1 的记录的所有 FOO 实例,并从 foo 中排除 foo.id 有一条记录为 n foo_bar_xref 且 bar_id 为 2 的记录
foo -> foo_bar_xref 是一对多 *强调文本*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.
那不是过滤掉 bar 为 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
【问题讨论】:
-
我喜欢你的左连接方法——我的想法也是如此。
标签: sql sql-server sql-server-2008