I have a MySQL query that I would like to enhance by requiring that all values of client.client_name are printed out in the result, even if no values are found for every row in that table. The current table shows:
client.client_name
Client A
Client B
Client C
The current MySQL query is below:
SELECT X.expr1 AS 'Project Name', SUM(X.expr2) AS 'Total Hours Logged', X.expr3 - sum(X.expr2) AS 'Monthly Hours Remaining', X.expr4 AS 'Last Day', DATEDIFF(X.expr4 , curdate()) AS 'Days Remaining'
FROM
(SELECT
client.client_name AS expr1
, sum(time_records.value) AS expr2
, client.monthly_hours AS expr3
FROM project_objects
INNER JOIN projects
ON projects.id = project_objects.project_id
INNER JOIN time_records
ON time_records.parent_id = project_objects.id
LEFT JOIN client
ON project_objects.project_id = client.project_id
WHERE time_records.parent_type = 'Task'
AND client.start_day_of_month < dayofmonth(curdate())
AND time_records.state = 3
GROUP BY client.client_name
UNION
SELECT
client.client_name AS expr1
, sum(time_records.value) as expr2
, client.monthly_hours AS expr3
FROM projects
INNER JOIN time_records
ON projects.id = time_records.parent_id
LEFT JOIN client
ON projects.id = client.project_id
WHERE time_records.parent_type = 'Project'
AND client.start_day_of_month < dayofmonth(curdate())
AND time_records.state = 3
GROUP BY client.client_name
) X
GROUP BY X.expr1
ORDER BY DATEDIFF(X.expr4 , curdate()
As you can see from the above query – I added a Left Join for the client table, however it doesn’t result in printing out all client records – it only prints those for which there are time_records available. I think this is related to the nesting or the order of how I am writing the joins, but can’t seem to figure it out. If you have any ideas it would be greatly appreciated. Thanks!
Please try order as below:
see SQLFiddle for the final solution here: http://sqlfiddle.com/#!2/30362/16