9amI got help with the query from a previous post but I have a new question.
Bear with me in my explanation….
Setup, 2 tables: cal_events which holds dynamic events for a calendar and recurring events that have an update made to them for a single day. Also, cal_events_recurring which holds recurring events.
The query below is an example with dummy data that would be passed by PHP.
I based it off of Dec 15th, so return every event for that day.
The important part is that the recurring event is only returned if it does not have a matching dynamic counterpart. If cal_events, is_overwrite = 1 and its overwrite_id = (the unique id of the 9:00 am cal_events_recurring event, then only return the dynamic table row.
This means, “Hey, I’m an event that occurs every day at 9:00am(example), but look, on Dec 15th the 9:00 recurring event has been updated for that day based on the dynamic table having my unique id = to its overwrite_id so return that one.”
select * from(
select
ifnull(ce.time, cer.time) as time,
ifnull(ce.title, cer.title) as title,
ce.is_overwrite
from cal_events_recurring cer
left join cal_events ce on ce.overwrite_id = cer.id
where cer.is_daily = 1
or cer.day_index = 6
or cer.day_num = 15
union
select time as time, title, is_overwrite
from cal_events where date = '2012-12-15'
and is_active = 1 and is_overwrite = 0) as e order by time asc
This is all well and fine, the data is correct, the problem is the is_active fields.
I’ll go off the 9:00am example again. I created a dynamic event for 9:00am for the 16th which will overwrite the recurring event on the 16th. Now if I later decide I want to revert back to the regular recurring event, I set the is_active field to 0 for the matching dynamic event. The problem is the dynamic event is still returned. If I add and ce.is_active = 0 the event is still returned. How would I write it so that it would still return the recurring event if its dynamic counterpart is not active?
Any other info you need let me know!
EDIT*
output :
time title
08:00:00 recurring everyday 8am
09:00:00 dynamic 9am update
(9am should be the recurring event because the dynamic is_active = 0)
Put that condition into the
ONclause:Putting the special condition into the join condition means you still get a left join, but only for rows that should be joined.
If you put the condition in the where clause, you’ll “break” the intention of the left join and the
ifnull(), here’s why:Conditions in the
ONclause of a join execute as the join is being made, so rows that you don’t want joined don’t get joined and don’t make their values into theifnull()function.It is a common misconception that join conditions can only be “key related”, when in fact they can be anything.
If you put the condition into the where clause, it is executed after the join is made – where clauses filter results sets, so it’s too late – the
ifnull()already has the dynamic table’s data.