我有一个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)
(实际上,无论我是否使用联合表,我都无法让它工作。)
答案 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