This probably has a simple solution to it but i can’t wrap my head around it at the moment.
My table looks like this
|id|company_id|shift_type_id|user_id|date|create_at|updated_at|
I’m trying to list shifts that belong to a specific user
SELECT * FROM shifts WHERE user_id = 1
Then make a selection between two dates
SELECT * FROM shifts WHERE user_id = 1 and date BETWEEN '2012-07-09' and '2012-07-15'
Exclude all shifts that are on Saturday and Sunday
SELECT * FROM shifts WHERE user_id = 1 and date BETWEEN '2012-07-09' and '2012-07-15' and DAYNAME(date) != "Saturday" and DAYNAME(date) != "Sunday"
Now the tricky part (for me), on top of all this i want to exclude shifts that are on Friday and with a specific shift_type_id in this case 6. I tried by doing this
SELECT * FROM shifts WHERE user_id = 1 and date BETWEEN '2012-07-09' and '2012-07-15' and DAYNAME(date) != "Saturday" and DAYNAME(date) != "Sunday" and (DAYNAME(date) != "Friday" and shift_type_id != 6)
This doesn’t work, i dont quite understand why and i dont know how to solve this problem. I’ve seen some solutions that use subqueries and exclude the results from the main results but i want keep this easy to build on so that i can create a query from a set of rules.
I’m doing this in a rails3 project and this is what that looks like
@user.work_hours.where('shifts.date between ? and ?', params[:start_date], params[:end_date]).where('DAYNAME(shifts.date) != "Sunday" and DAYNAME(shifts.date) != "Saturday" AND (DAYNAME(shifts.date) != "Friday" and shifts.shift_type_id != 6)')
From what you’ve said you need
Exclude fridays with a shift id of 6, yours was exclude fridays that don’t have an id of 6.