I'm not sure if I'm missing something really obvious, but I keep getting a syntax error on this query. Even if I AM missing something obvious, I'd like to know if there is a smarter way of getting what I'm after.
Basically, the query asks for any rows tied to a user with a start_date between Monday and Friday. That works great. But then I added a conditional query in case there are any rows for that Saturday or Sunday. Note that the conditional query is checking for ANY users with a Saturday or Sunday, not the user in the main query:
SELECT user_id,
DATE_FORMAT(DATE(shift_start),'%m/%d/%Y') date,
TIME_FORMAT(TIME(shift_start), '%h:%i %p') start,
TIME_FORMAT(TIME(shift_end), '%h:%i %p') end,
title
FROM shifts
WHERE user_id = '$user_id'
AND DATE(shift_start) BETWEEN
DATE_SUB(DATE(NOW()), INTERVAL WEEKDAY(NOW()) DAY) AND
DATE_ADD(DATE(NOW()), INTERVAL
(SELECT
IF(
COUNT(*) FROM shifts
WHERE DATE(shift_start) BETWEEN
DATE_ADD(DATE(NOW()), INTERVAL 5 - WEEKDAY(NOW()) DAY) AND
DATE_ADD(DATE(NOW()), INTERVAL 6 - WEEKDAY(NOW()) DAY),
6, 4)) - WEEKDAY(NOW()) DAY)
ORDER BY shift_start
I'm actually pretty proud of how it works before it messes up with the IF part, but again, if there is an obviously better way doing this, I'm all ears.
Oh, and when this gets ironed out, the "Now()" will be replaced with a date variable set up in the php script (passed to it via GET).
Thanks!
Awesome job, benlumey. Here's what worked:
SELECT user_id,
DATE_FORMAT(DATE(shift_start),'%m/%d/%Y') date,
TIME_FORMAT(TIME(shift_start), '%h:%i %p') start,
TIME_FORMAT(TIME(shift_end), '%h:%i %p') end,
title
FROM shifts
WHERE user_id = '$user_id'
AND DATE(shift_start) BETWEEN
DATE_SUB(DATE(NOW()), INTERVAL WEEKDAY(NOW()) DAY) AND
DATE_ADD(DATE(NOW()), INTERVAL
(SELECT
IF(COUNT(*),6,4)
FROM shifts
WHERE DATE(shift_start) BETWEEN
DATE_ADD(DATE(NOW()), INTERVAL 5 - WEEKDAY(NOW()) DAY) AND
DATE_ADD(DATE(NOW()), INTERVAL 6 - WEEKDAY(NOW()) DAY))
- WEEKDAY(NOW()) DAY)
ORDER BY shift_start