title: MySQL event-based support ticket system
body: <p>Afternoon all.</p>
  
  <p>I've recently been tasked with working on an event-based support ticket system, but I've encountered a lot of issues and I think the problem is the database structure.</p>
  
  <p>At the moment it looks a bit like this:</p>
  
  <pre><code>create table tickets (
      ticket_id int not null primary key auto_increment,
      stage_id int not null default 0,
      name varchar(255) not null default ''
      /* etc... */
  );
  create table ticket_events (
      event_id int not null primary key auto_increment,
      ticket_id int not null,
      date datetime,
      stage_id
  );
  create table stages (
      stage_id int not null primary key auto_increment,
      name varchar(255)
  );
  </code></pre>
  
  <p>So whenever a ticket changes stage a new row is added to the ticket_events table specifying which stage it moved to and when, and the stage_id field in the tickets table is updated with the new stage.</p>
  
  <p>The problem is that this breaks database normalisation rules, as a ticket has its current stage defined by both tickets.stage_id and the most recent record in the ticket_events table. In my attempt to write a report showing the number of outstanding tickets at any point in time I've discovered why it is this way. It seems that it's very difficult to get any kind of SQL to quickly retrieve the current stage from the events table.</p>
  
  <p>I managed to construct a reasonably fast query using option 2 at this very helpful page (http://kristiannielsen.livejournal.com/6745.html), but I've come across an issue that leaves me stuck.</p>
  
  <p>With the current data the event_id does not always run in ascending order relative to date. In addition, due to certain automated processing scripts it is quite possible that one ticket has two events with exactly equal dates. The means that any query trying to use the events table needs to "order by date, event_id", which is almost impossible to do with subqueries and grouping.</p>
  
  <p>Can anyone give any advice for how I might go about overcoming these issues? Is there a better way of defining the order of events?</p>
  
  <p>Many thanks.
  Simon</p>