I'm currently working on a simple employee scheduling tool and have a problem with a SQL query. To explain my problem let use this two very abstract tables.
The first table simply consists of the employees
employees ====================== empId | name | ... ---------------------- 10 | Scott | 11 | Schrute | 12 | Halpert | 13 | Howard |
In the second table you find the assigned tasks to each employee by day.
tasks ============================================== tasId | name | task | date | ... ---------------------------------------------- 10 | Scott | Support | 2014-02-17 | 11 | Scott | Bugfix | 2014-02-18 | 12 | Halpert | Bugfix | 2014-02-17 | 13 | Halpert | Develop | 2014-02-18 | 14 | Howard | Support | 2014-02-17 |
Now I want to know what the employees are working on on Feb 17th or if they have no tasks planned for that day. I use the following SQL query to do that.
SELECT e.name, t.task
FROM employees e LEFT JOIN tasks t ON e.name = t.name
WHERE date IS NULL OR date = DATE('2014-02-17')
The result delivers exactly what I need:
name | task -------------------- Scott | Support Schrute | NULL Halpert | Bugfix Howard | Support
And now to my problem. If I want to see the tasks of Feb 18th I get this result set:
name | task -------------------- Scott | Bugfix Schrute | NULL Halpert | Develop
The reason to this is obvious, the date of Howard's tasks are neither NULL nor do they equal 2014-02-18.. What would be the best way to get the desired result?
I use MySQL and PHP.
(Sorry for the stupid title, I couldn't think of anything better..)
Move your filter to the join predicate:
SELECT e.name, t.task
FROM employees e
LEFT JOIN tasks t ON e.name = t.name AND t.date = DATE('2014-02-18');
Your query as it is will only return people who have no tasks at all, or have tasks on the date specified. It will omit people who have tasks, but not on the date specified. Consider the results of joining your sample data with no where clause:
empId | name | task | date | ...
----------------------------------------|
10 | Scott | Support | 2014-02-17 |
10 | Scott | Bugfix | 2014-02-18 |
11 | Schrute | NULL | NULL |
12 | Halpert | Bugfix | 2014-02-17 |
12 | Halpert | Develop | 2014-02-18 |
13 | Howard | Support | 2014-02-17 |
As you can see there is no record for Howard where Date
= 2014-02-18, or where Date
is null, this is why no record is returned for Howard. When you add the filter to the join predicate your results become:
empId | name | task | date | ...
----------------------------------------|
10 | Scott | Bugfix | 2014-02-18 |
11 | Schrute | NULL | NULL |
12 | Halpert | Develop | 2014-02-18 |
13 | Howard | NULL | NULL |
Which I think is the desired results.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments