通过join从数据库中获取空条目

时间:2013-12-05 08:02:43

标签: sql sql-server-2012

我有两张桌子就是出席场地

ID          UserID      isPresent InTime           OutTime          Date
----------- ----------- --------- ---------------- ---------------- -----------------------
1           1           p         10:00:00.0000000 18:00:00.0000000 2013-01-01 00:00:00.000
2           2           P         10:00:00.0000000 18:00:00.0000000 2013-01-02 00:00:00.000
3           2           p         10:00:00.0000000 18:00:00.0000000 2013-01-03 00:00:00.000

And a user table 

USerID      UserName
----------- ----------------------------------------------------------------------------------------------------
1           test
2           test1
3           test2
4           test3
5           test4
6           test5
7           test6

我有一个查询来获得所有员工的注意力,如果它是null,则将intime和Outtime显示为null

我的查询是

SELECT u.ID as UserID, isPresent, day(Date) as day FROM users u
  join EmployeeAttendance e on e.USerID = u.ID 

  where [Date] between 'Jan  1 2013 12:00AM' and 'Jan 31 2013 11:59PM'

但此查询仅提供出勤表中的结果,如

UserID      isPresent day
----------- --------- -----------
1           p         1
2           P         2
2           p         3

但我需要

    UserID      isPresent   day
    ----------- -------   -- -----------
    1           p         1
    2           P         2
    2           p         3
    3           NULL      Null
    4           NULL      Null
    5           NULL      Null
    6           NULL      Null
    7           NULL      Null

任何想法我应该怎么做到这一点..

由于

3 个答案:

答案 0 :(得分:1)

使用右外连接而不是连接

答案 1 :(得分:1)

LEFT JOIN

SELECT u.ID as UserID, isPresent, day(Date) as day FROM users u
 LEFT join EmployeeAttendance e on e.USerID = u.ID 

  where [Date] between 'Jan  1 2013 12:00AM' and 'Jan 31 2013 11:59PM'

答案 2 :(得分:1)

SELECT u.id      AS UserID, 
       ispresent, 
       Day(date) AS day 
FROM   users u 
       LEFT JOIN employeeattendance e 
              ON e.userid = u.id 
WHERE  [date] BETWEEN 'Jan  1 2013 12:00AM' AND 'Jan 31 2013 11:59PM'