开发者

Is a cursor the only way to do this?

I'm in the process of churning through some raw data that I have. The data are in a MySQL database. The data lists, in a millisecond-by-millisecond format, which of a number of possible 'events' are currently happening. It has only a few columns:

  1. id - unique identifier for the row
  2. event - indicates which event is currently occurring

What I would like to do is get some basic information regarding these data. Specifically, I'd like to create a table that has:

  1. The id that an event starts
  2. The id that an event ends
  3. A new id indexing the events and their occurrence, as well as a column detailing which event is currently happening.

I know that this would be easy to deal with using PHP, just using a simple loop through all the records, but I'm trying to push the boundaries of my MySQL knowledge for a bit here (it m开发者_开发知识库ay be dangerous, I know!!).

So, my question is this: would a cursor be the best thing to use for this? I ask because events can occur multiple times, so doing something like grouping by the event type won't work - or will it? I'm just wondering if there is a clever way of dealing with this I have missed, without needing to go through each row sequentially.

Thanks!


To demonstrate what I commented earlier about, say you have the following table:

event_log
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY
  start DATETIME
  event VARCHAR(255)                     # or whatever you want for datatype

Gathering this information is as simple as:

SELECT   el.*,
         (SELECT   el_j.start            # -
          FROM     event_log el_j        #  |
          WHERE    el_j.id > el.id       #  |- Grab next row based on the next ID
          LIMIT    1) as end             # -
FROM     event_log
ORDER BY start;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜