SQL用于查找在不同表中没有记录类型的记录

时间:2014-07-02 15:07:52

标签: sql sql-server sql-server-2008

我正在尝试编写一些查询两个表的SQL,并将另一个表中没有特定类型记录的记录带回来。

如果表1是具有EmpID,姓名,姓氏的员工表。

,第二张表是预订ID,EmpID,年份

我想查找2014年没有预订的所有记录。

所以如果员工表是:

EMPID   Name   Surname

1        John   Doe
2        Bob    Smith

和预订表是

Booking ID   Emp ID   Year
1             1        2013
2             1        2014
3             2        2012
4             2        2013

我只希望sql

4 个答案:

答案 0 :(得分:3)

 SELECT * FROM employee
 LEFT JOIN Booking ON Booking.empid = employee.empid AND year = 2014
 WHERE Booking.empid IS NULL

答案 1 :(得分:2)

使用WHERE检查添加NOT EXISTS子句,以过滤所需的记录:

SELECT e.EMPID, e.[Name], e.Surname
FROM Employee e
WHERE NOT EXISTS 
      (SELECT EmpID 
       FROM Booking b 
       WHERE b.BookingId = e.EmpId and b.Year = 2014)

Sample SQL Fiddle

供参考,这是SQL Fiddle创建/插入脚本:

create table employee(EMPID int, Name varchar(50), Surname varchar(50))
create table booking(BookingID int, EmpID int, Year int)

insert into employee (EMPID, Name, Surname) values(1,'John','Doe')
insert into employee (EMPID, Name, Surname) values(2,'Bob','Smith')

insert into booking(BookingID,EmpID,Year) values(1,1,2013)
insert into booking(BookingID,EmpID,Year) values(2,1,2014)
insert into booking(BookingID,EmpID,Year) values(3,2,2012)
insert into booking(BookingID,EmpID,Year) values(4,2,2013)

答案 2 :(得分:2)

一个经常过度看待的解决方案是EXCEPT。这是SQL Server特定的语法,基本上与UNION

相反
SELECT 
       e.EMPID,
       e.Name,
       e.Surname
FROM
      employee e
EXCEPT
SELECT 
       e.EMPID,
       e.Name,
       e.Surname
FROM
      employee e 
      INNER JOIN Booking B
      ON e.empID = b.empid
WHERE
       b.year = 2014

DEMO

另一个被忽略的语法是!= ANY,而且与NOT IN之间的主要区别在于你不必担心预订中的null empId

SELECT 
       EmpId, Name 
FROM   employee e
WHERE  empid != ANY (SELECT empid 
                     FROM   booking 
                     WHERE  year = 2014) 

DEMO

答案 3 :(得分:1)

 select * from employee
   where empid not in
   (select empid from Booking
        where year = 2014)

当然,只有说明“选择*”通常不是一件好事,最好还是返回你特别想要的列...

但是,如果您的预订表包含空EmpIds,您可以使用以下内容来满足它:

select * from employee
   where empid not in
   (select empid from Booking
        where year = 2014 and empid is not null)