使用LEFT JOIN时没有收到预期的结果?

时间:2012-06-12 08:55:08

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

我有以下SQL语句,即使我有300名员工,它也只返回2条记录。有谁看到我可能做错了什么?

SELECT     Employees.[Employee ID], 
Employees.Employee, 
Employees.[First Name], 
Employees.[Middle Name], 
Employees.[Last Name], 
Employees.Position,
[Work].[Work ID]
FROM  Employees LEFT JOIN
[Work] ON Employees.[Employee ID] = [Work].[Employee ID]
WHERE [Work].[Work Date] = '06-13-2012'

4 个答案:

答案 0 :(得分:3)

在外表上使用外连接过滤器时必须在ON子句中应用,否则有效地获得内连接:

SELECT     
    Employees.[Employee ID], 
    Employees.Employee, 
    Employees.[First Name], 
    Employees.[Middle Name], 
    Employees.[Last Name], 
    Employees.Position,
    [Work].[Work ID]
FROM  Employees 
LEFT JOIN [Work] 
  ON Employees.[Employee ID] = [Work].[Employee ID]
 AND [Work].[Work Date] = '06-13-2012'

答案 1 :(得分:2)

如果您想要所有员工,也许您正在寻找以下内容:

SELECT     Employees.[Employee ID],  ...
FROM  Employees LEFT JOIN 
[Work] ON Employees.[Employee ID] = [Work].[Employee ID] 
AND [Work].[Work Date] = '20120613' 

另请注意,您应使用明确的日期格式,例如YYYYMMDD

答案 2 :(得分:0)

您是否在Where子句中检查了日期?

尝试转换为日期时间或检查您是否在[工作]。[工作日期]列数据中定义了小时/分钟/秒。

尝试删除联接以查看问题所在:

SELECT [Work].[Employee ID], [Work].[Work ID]
FROM [Work]
WHERE [Work].[Work Date] = '06-13-2012'

您有多少条记录? 所有员工ID是否与Employees表中的ID匹配?

如果您需要所有员工而不是您应该进行LEFT OUTER JOIN:

SELECT     Employees.[Employee ID], 
Employees.Employee, 
Employees.[First Name], 
Employees.[Middle Name], 
Employees.[Last Name], 
Employees.Position,
[Work].[Work ID]
FROM  Employees LEFT OUTER JOIN
[Work] ON Employees.[Employee ID] = [Work].[Employee ID]
AND [Work].[Work Date] = '06-13-2012'

这是你想要的吗?

答案 3 :(得分:0)

还尝试查看[工作日期]栏 - 如果它还有时间部分(日期时间数据类型),那么你应该考虑到这一点:

SELECT     
    Employees.[Employee ID], 
    Employees.Employee, 
    Employees.[First Name], 
    Employees.[Middle Name], 
    Employees.[Last Name], 
    Employees.Position,
    [Work].[Work ID]
FROM  Employees 
LEFT JOIN [Work] 
  ON Employees.[Employee ID] = [Work].[Employee ID]
WHERE Convert(Char(10), [Work].[Work Date], 120) = '2012-06-13' -- can find better way