SQL查询:如何从没有记录或count = 0的其他表中选择记录(有条件的)

时间:2013-07-25 15:27:01

标签: sql sql-server select

我有两张桌子:

表1:StaffDB

SID | Name
1   | Peter
2   | Mary
3   | John

表2:就业历史(员工将有超过1条记录)

HistID | SID | PositionID | isCurrent | StartDate  | EndDate  
1      | 1   | 123        | 0         | dd-mm-yyyy | dd-mm-yyyy  
2      | 1   | 221        | 1         | dd-mm-yyyy |  
3      | 2   | 434        | 0         | dd-mm-yyyy | dd-mm-yyyy

例如,在表2中。

Peter (SID=1) had 2 records, 2nd record is current record (isCurrent=1)  

Mary (SID=2) had 1 non current record  

John (SID=3) don't have any record

如何编写SQL查询以选择没有任何工作经历或没有任何当前记录的员工(isCurrent = 1)

对于上面的例子,应该返回Mary和John。

由于

1 个答案:

答案 0 :(得分:5)

使用LEFT JOIN并检查连接表上的NULL主键:

SELECT StaffDB.*
FROM StaffDB
LEFT JOIN EmploymentHistory ON StaffDB.SID = EmploymentHistory.SID
  AND EmploymentHistory.isCurrent = 1
WHERE EmploymentHistory.HistID IS NULL

或使用EXISTS - 这可能会更高效,但不易读取(主观):

SELECT *
FROM StaffDB
WHERE NOT EXISTS (SELECT 1 FROM EmploymentHistory 
                  WHERE EmploymentHistory.SID = StaffDB.SID
                  AND EmploymentHistory.isCurrent = 1)