0

我有以下 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

4 回答 4

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'
于 2012-06-12T09:07:42.540 回答
2

如果您想要所有员工,也许您正在寻找类似的东西:

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

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

于 2012-06-12T09:08:36.753 回答
0

还可以尝试查看 [Work Date] 列 - 如果它也有时间部分(DateTime 数据类型),那么您应该考虑到这一点:

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
于 2012-06-12T14:59:44.540 回答
0

您是否检查过 Where 子句中的日期?

尝试转换为日期时间或检查 [Work].[Work Date] 列数据中是否没有定义小时/分钟/秒。

尝试删除连接以查看问题出在哪里:

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

你有多少这样的记录?是否所有员工 ID 都与员工表中的 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'

这是你想要的吗?

于 2012-06-12T08:58:20.563 回答