Question

I try to create an application for the iPhone where you can set appointments. Everything is saved into a MySQL database and I currently get the data through JSON into my app. This is a workflow

  1. User1 defines when he is working. E.g. 8am - 4pm.
  2. User2 wants to have an appointment with user1, e.g. 8am-9am.

When there is no current existing appointment, it can be saved. If there is already one, e.g. 8.15am - 8.45am, an error will be shown.

Can you please give me a hint how to do this? I was thinking about a class with NSDate "startDate" and "endDate", but I am not sure how to detect those appointment-collisions.

Thanks a lot, every hint is appreciated.

Was it helpful?

Solution

The appointment is valid iff the following conditions are met:

  • the appointment is within the user's work hours; and

  • it does not clash with an existing appointment, which can happen in three possible ways:

    • the clashing appointment starts during the new appointment; and/or

    • the clashing appointment ends during the new appointment; or

    • the clashing appointment starts before and ends after the new appointment.

You can query for this in pure SQL with something along the following lines:

SELECT EXISTS (
  SELECT *
  FROM   appointments a JOIN workhours h USING (user_id)
  WHERE  user_id = 1
     AND h.start <= '08:00:00' AND h.end >= '09:00:00'
     AND (
               a.start BETWEEN '08:00:00'  AND  '09:00:00'
           OR  a.end   BETWEEN '08:00:00'  AND  '09:00:00'
           OR (a.start < '08:00:00' AND a.end > '09:00:00')
         )
  LIMIT  1
)

Beware to perform this SELECT using a locking-read within a transaction in order to prevent concurrency issues.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top