php - Need help with this MySQL query. Finding users who are available at a certain time -
here simplified schema of database:
users ------------------------------------ userid | name | assignable ------------------------------------ 5 | john doe | 1 timeslots ------------------------------------------------------- timeslotid | starttime | endtime ------------------------------------------------------- 3 | 2011-06-30 15:00:00 | 2011-06-30 16:00:00 appointments ------------------------------------ timeslotid | userid ------------------------------------ 3 | 5
i have users can assigned timeslots make appointments. need way start start , end time , query users able assigned (assignable flag set 1) , have no time conflicts (appointments overlap) times.
older timeslots in there interested in timeslots or in future.
select * users u u.assignable = 1 , u.userid not in ( select userid appointments join timeslots t on a.timeslotid = t.timeslotid t.endtime > now() , t.endtime > @desiredstarttime , t.starttime < @desiredendtime )
edit taking cue tandu
i think work, , has added performance benefit of no subqueries:
select * users u left join appointments on a.userid = u.userid left join timeslots t on ( a.timeslotid = t.timeslotid , t.endtime > now() , t.endtime > @desiredstarttime , t.starttime < @desiredendtime ) u.assignable = 1 , t.timeslotid null
Comments
Post a Comment