SQl列出行,如果不在另一个表中

时间:2010-03-22 14:08:50

标签: tsql sql

我有以下查询,其中包含1000行

select 
staffdiscountstartdate,datediff(day,groupstartdate,staffdiscountstartdate),
EmployeeID 
from tblEmployees 
where GroupStartDate < '20100301' and StaffDiscountStartDate > '20100301' 
and datediff(day,groupstartdate,staffdiscountstartdate)>1 
order by staffdiscountstartdate desc

我有以下有400行的查询:即tmpmployees和tblcards中的员工

select a.employeeid,b.employeeid 
from tblEmployees a,tblCards b 
where GroupStartDate < '20100301' 
and StaffDiscountStartDate > '20100301' 
and datediff(day,groupstartdate,staffdiscountstartdate)>1 
and a.employeeid=b.employeeid 

如何列出员工中的员工而不是tblcards?

即1000-400 = 600行???

4 个答案:

答案 0 :(得分:1)

select 
    a.employeeid,
    b.employeeid 
from 
    tblEmployees a
        left join
    tblCards b 
        on
            a.employeeid=b.employeeid 
where 
    GroupStartDate < '20100301' 
and 
    StaffDiscountStartDate > '20100301' 
and 
    datediff(day,groupstartdate,staffdiscountstartdate)>1 
and
    b.employeeid is null

答案 1 :(得分:1)

使用左连接来连接表,然后过滤表tblCards为空的位置。

select  
    a.employeeid 
from  
    tblEmployees a
left outer join
    tblCards b
on
    a.employeeid=b.employeeid
where  
    GroupStartDate < '20100301'  
and  
    StaffDiscountStartDate > '20100301'  
and  
    datediff(day,groupstartdate,staffdiscountstartdate)>1  
and  
    b.employeeid IS NULL

答案 2 :(得分:0)

  

如何列出员工   那里有职员而不是   tblcards?

select employeeid from tblEmployees 
   where employeeid not in 
   (select employeeid from tblCards)

答案 3 :(得分:-1)

 SELECT emp.EmployeeID
 FROM   tblEmployees AS emp
      LEFT JOIN tblCards AS crd ON (emp.EmployeeID = crd.EmployeeID)
 WHERE  (crd.EmployeeID IS NULL)