Skip to content
Advertisement

MySQL selecting entries when true and replace with null when false

I am programming an office schedule.

I have a table users in which each user has a regular schedule hreg that is monday to friday.

I have a table hleave in which I enter a leave code for the dates a user is out of office.

Table hleave:

Table users:

Table teams:

Table hreg:

Table leave_codes:

If there is an hleave entry with a date range that either starts this week, ends this week or starts before this week and ends after this week, I want to display the leave code.

If not, I want to display the user’s regular schedule “working”. For example:

Here is my query for TEAM #1 (I replaced the variables $monday and $friday with real dates for clarity) :

Results:

This query works. I get the codeName, dateStart and dateEnd for a user if it happens this week. If dateStart and dateEnd are NULL, I still get the user firstName, lastName and hreg so I can display them on the website as working.

So far so good, but I have a problem. When dateStart < '2019-02-25' and dateEnd < '2019-03-01' (i.e. if the leave happened before this week) I get nothing for this user since the date range validates as FALSE and it is not NULL either. For instance, if Roger had a leave on 2019-02-11 to 2019-02-13, Roger is not included in the results set.

Same thing goes for a date range in the future : dateStart > '2019-02-25' and dateEnd> '2019-03-01'.

What would be the best way to achieve this? I tried CASE WHEN in the SELECT clause to pin poit the dates I want to select but the result is the same. I either need to select differently or to turn entries validating as FALSE to NULL?

Advertisement

Answer

As I noted in my comment, it appears that you’re making the query a bit more complex than needed.

The main issue is the CASE/WHEN in your WHERE criteria, limiting the users to those matching in the CASE/WHEN, Since Roger was on leave, but did not match the specified dates in the WHERE criteria, he was excluded.

As you appear to only be interested in a specific team, the user team can be filtered directly in your main query. Presuming hleave only contains an entry when the user is on leave for the date range queried, the condition can be moved from your WHERE to the LEFT JOIN, displaying NULL when the user is not on leave.

Results in:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement