使用Joined-Tables排除某些记录

Ire*_*ene 2 sql sql-server join sql-server-2005 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)
Run Code Online (Sandbox Code Playgroud)

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

Ric*_*iwi 9

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

select * from table1 t1
where not exists (
    select * from table2 t2
    where t2.employeeA = t1.employee
       or t2.employeeB = t1.employee)
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)