0

我有一张用户表和一张时间条目表。我正在尝试获取sum(time_entry.hours_worked)日期在值范围内的每位员工。

和:

SELECT employee.id, COALESCE(SUM(time_entry.hours_worked),0) as `sum`
FROM employee 
LEFT JOIN time_entry 
ON employee.id = time_entry.student_id
GROUP BY employee.id;

即使没有工作时间,我也可以获得所有员工的条目:

+----+--------+
| id | sum    |
+----+--------+
|  1 | 191.00 |
|  2 |  48.00 |
|  3 |   0.00 |
+----+--------+

使用 where 语句:

SELECT employee.id, COALESCE(SUM(time_entry.hours_worked),0) AS `sum`
FROM employee 
LEFT JOIN time_entry 
ON employee.id = time_entry.student_id
WHERE time_entry.date < 1367798400
GROUP BY employee.id;

我得到一个空集。WHERE当在数据库中找不到条目时,如何使用该语句并仍然为每个员工获得 0?

4

1 回答 1

0

问题是条件在left outer join. 当没有匹配时,所有列都设置为NULL。因此,该where子句失败。事实上,这样的条件就是把left outer joinback 变成inner join.

要解决此问题,请将条件移至on子句:

SELECT employee.id, COALESCE(SUM(time_entry.hours_worked),0) AS `sum`
FROM employee 
LEFT JOIN time_entry 
ON employee.id = time_entry.student_id and
   time_entry.date < 1367798400
GROUP BY employee.id;
于 2013-06-05T21:48:58.487 回答