0

I have a table of users and a table of time-entries. I am trying to obtain the sum(time_entry.hours_worked) per employee where the date is within a range of values.

With:

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;

I am able to obtain entries for all employees, even if no hours are worked :

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

With a where statement:

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;

I obtain an empty set. How can I use the WHERE statement and still obtain 0 per employee when no entries are found in the database?

4

1 に答える 1

0

問題は、条件が の 2 番目の表にあることleft outer joinです。一致するものがない場合、すべての列が に設定されNULLます。したがって、where句は失敗します。実際、そのような状態はleft outer join背中を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 に答える