使用Joined-Tables排除某些记录

时间:2011-01-22 03:12:29

标签: sql sql-server sql-server-2005 join outer-join

我有一个SQL Server 2005 表(#1),其中列出了员工姓名以及有关每个人的各种信息。

我有第二个表(#2),其中列出了我希望从结果中排除的一些员工。 (员工姓名可以出现在两列中:A和B。)

我可以将联合表用于EXCLUDE吗?

列出Fred中名为table #1的所有员工...但排除table #2中列出的某位员工。 如果Fred Smith中列出table #2(在2个字段中的任意一个中),请不要在我的结果中列出他。 (但列出Fred

中的所有其他table #1条记录
SELECT * 
FROM table1 AS t1, table2 AS t2
WHERE ('Fred Smith' <> t2.employeeA) AND ('Fred Smith' <> t2.employeeB)

(实际上,无论我是否使用联合表,我都无法让它工作。)

1 个答案:

答案 0 :(得分:9)

有多种方法可以写这个,但性能最好的(通常,数据分布可以改变这个)通常是存在测试。也很容易理解所写的确切意图。

select * from table1 t1
where not exists (
    select * from table2 t2
    where t2.employeeA = t1.employee
       or t2.employeeB = t1.employee)

您也可以尝试其他方式,看看哪种方式更适合您

select t1.*
from table1 t1
left join table2 t2 on
  t2.employeeA = t1.employee or t2.employeeB = t1.employee
where t2.id is null   -- check that the join failed by testing against the PK of t2