Access中的SQL查询列出了不在两个表中的值

时间:2012-10-26 15:18:13

标签: sql ms-access

我需要找出过去6个月内哪些司机没有购买燃料。

我有两个表TransactionReport(过去6个月的所有交易)和DriverList(所有驱动程序)

TransactionReport
DriverID  |  DriverLastName | DriverFirstName | Other Columns not used for this query

DriverList
DriverID  |  DriverLastName | DriverFirstName | Other Columns not used for this query

我想返回DriverList中未列出的DriverList中列出的所有DriverID。

结果应该给我以下

DriverID  |  DriverLastName | DriverFirstName

4 个答案:

答案 0 :(得分:3)

左外连接只在右表中获得NULL结果应该可以正常工作

select distinct driverlist.driverid, driverlist.driverlastname, driverlist.driverfirstname
from driverlist
left outer join transactionreport
on driverlist.driverid = transactionreport.driverid
where transactionreport.driverid is null

答案 1 :(得分:2)

select 
    DriverID, DriverLastName, DriverFirstName

from
    DriverList

where
    DriverID not in (select DriverID from TransactionReport)

答案 2 :(得分:1)

SELECT dl.DriverID , dl.DriverLastName, dl.DriverFirstName FROM DriverList dl
 LEFT JOIN TransactionReport tr ON  dl.DriverID  = tr.DriverID  
WHERE tr.DriverID IS NULL

答案 3 :(得分:0)

你可以像前面提到的那样做:

Select dl.DriverID , dl.DriverLastName, dl.DriverFirstName From DriverList dl
 LEFT Join TransactionReport tr on  dl.DriverID  = tr.DriverID  
WHERE tr.DriverID is Null

哪个会奏效。但是,使用反半连接可以获得更快的结果和更可读的查询。似乎MS Access的更高版本支持这一点:

SELECT dl.DriverID, dl.DriverLastName, dl.DriverFirstName From DriverList dl
WHERE NOT EXISTS (
     SELECT tr.DriverID 
     FROM TransactionReport tr 
     WHERE tr.DriverID = dl.DriverID)

这里的关键是要注意EXISTS语句中的WHERE。 NOT逻辑已经在EXISTS前面,所以你必须在语句中测试相等性。