开发者

Using Joined-Tables to exclude certain records

开发者 https://www.devze.com 2023-02-06 16:08 出处:网络
I have a SQL Server 2005 table (#1) that list employee names, and various info about each of them. I have a second table (#2) that lists some of the employees that I wish to exclude from my results.

I have a SQL Server 2005 table (#1) that list employee names, and various info about each of them.

I have a second table (#2) that lists some of the employees that I wish to exclude from my results. (The employee names could appear in either of 2 columns: A and B.)

Can I use joined-tables to EXCLUDE?

List all e开发者_StackOverflow中文版mployees named Fred in table #1... but exclude a certain employee listed in table #2. If Fred Smith is listed in table #2 (in either of 2 fields), don't list him in my results. (but list all other Fred records from table #1)

SELECT * 
FROM table1 AS t1, table2 AS t2
WHERE ('Fred Smith' <> t2.employeeA) AND ('Fred Smith' <> t2.employeeB)

(Actually I can't get it to work regardless of whether I use joined-tables, or not.)


There are various ways to write this, but the best performing one (normally, data distribution can change this) is normally the existence test. It is also easy to understand the exact intention as written.

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

You can always try another way as well to see which works better for you

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
0

精彩评论

暂无评论...
验证码 换一张
取 消