I have a query,
SELECT E.staffid AS staff
SUM(E.Frequency='Less') AS lessCount,
SUM(E.Frequency='More') AS moreCount,
FROM effort_frequency E
INNER JOIN ost_staff S ON S.staff_id = E.staffid
WHERE E.log_date BETWEEN '2012-05-01' AND '2012-05-23'
GROUP BY E.staffid
I get the below table,
+-------+-----------+-----------+
| Staff | lessCount | moreCount |
+-------+-----------+-----------+
| 1 | 2 | 3 |
| 3 | 1 | 4 |
| 5 | 2 | 3 |
+-------+-----------+-----------+
You can see that the 2 & 4 is missing in the result, There will be no rows with staff_id 2 & 4 in the effort_frequency table for the given date, but I’m trying to join the ost_staff table, so that I can get something like the below table, The ost_staff will contain all the staff id, lets say 1-5.
+-------+-----------+-----------+
| Staff | lessCount | moreCount |
+-------+-----------+-----------+
| 1 | 2 | 3 |
| 2 | 0 | 0 |
| 3 | 1 | 4 |
| 4 | 0 | 0 |
| 5 | 2 | 3 |
+-------+-----------+-----------+
I tried outer joins but its not working, I think I’m making mistake somewhere.
Move the
WHEREclause toONclause, and change theINNER JOINtoRIGHT JOIN. And change theGROUP BY E.staffidtoGROUP BY S.staff_id; likewise withSELECT E.staffid,change it toSELECT s.staff_id:If you want to use
LEFT JOIN, switch the tables ost_staff and effort_frequency:You can also use IFNULL in lieu of COALESCE. IFNULL works only on MySQL though