I am facing a situation and need help. I have two tables:
user:
user_id,fname,lname,email.
user_timesheet:
time_id,user_id,month,state,date.
Users are to add time to user_time table with the state as = ‘no’ and at the end of the month they submit that time which change the state = ‘yes’ assuming the month is JUNE
I want to write a query that will bring all users who did not add time at all and users who have added time but has not submit for JUNE.
This is my query.
SELECT user_timesheet.time_id, user_timesheet.user_id,
user_timesheet.month, user_timesheet.`state`,
`user`.user_id, `user`.fname, `user`.lname,
`user`.email
FROM user LEFT JOIN
user_timesheet ON user.user_id=user_timesheet.user_id
WHERE (
user_timesheet.state = 'no' OR
user_timesheet.state IS NULL)
AND (
user_timesheet.month = 'june' OR
user_timesheet.month IS NULL)
GROUP BY user.user_id
The result bring all users who have added time in june but have submitted it and also the users who have NEVER ADDED TIME to the system since they join. It however does not bring users who have either added time or submitted time in the previous month but has not added time at all for june.
Instead of (a = x or a is null) in where clause put your filter in ON clause. This will remove non-matching records but preserve nature of left join.
To treat ‘no’ status as non existant row filter it out of left join:
Note: I don’t know what is comment marker in MySql. It is — in Sql Server, so delete this lines before you try the query.