I have a table of events generated by users doing stuff. It looks roughly like this:
session | time | event | etc.
06efaa1805ef670c | 2022-01-07 08:41:03 | lockFound | etc.
06efaa1805ef670c | 2022-01-07 08:41:43 | lockLost | etc.
154032b09bec72f8 | 2022-01-07 10:41:03 | lockFound | etc.
154032b09bec72f8 | 2022-01-07 10:41:43 | lockLost | etc.
I need to get all of these events in a certain order:
- They have to be grouped by the session ID so all events from one session appear together
- The sessions have to be in order of time (preferably the time of the first event in the session)
- The order of the events in the session doesn't actually matter
- I don't want to use GROUP BY because I need every event in the table
How would I set about this?
The actual data is here
Retrieved by:
SELECT * FROM dlrcoco_events ORDER BY time DESC`
If using MySQL 8 or later then you can use window functions:
Explanation of order by:
sessionas second column. This ensures rows belonging to same session remain together.The window function could be replaced with a correlated sub query: