Say I have a table Connections
with format [logID, user, time]
An example set be:
| logID | user | time
|-----------------------
| 91 | terry | 12:55:00 <--- Last by user
| 90 | terry | 12:54:26
| 89 | nami | 12:52:12 <--- Last by user
| 88 | terry | 12:50:50 <--- Last by user
| 87 | terry | 12:49:21
| 86 | terry | 12:48:16
| 85 | terry | 12:46:07
| 84 | nami | 12:31:22 <--- Last by user
| 83 | nami | 12:30:30
| 82 | nami | 12:29:26
| 81 | terry | 12:27:12 <--- Last by user
The desired query should GROUP the user column whenever it changes and select the last timestamp by that user:
| logID | user | time
|-----------------------
| 91 | terry | 12:55:00 <--- Last by user
| 89 | nami | 12:52:12 <--- Last by user
| 88 | terry | 12:50:50 <--- Last by user
| 84 | nami | 12:31:22 <--- Last by user
| 81 | terry | 12:27:12 <--- Last by user
I've been playing around with GROUP BY, but haven't gotten anywhere...
One way would be using user variables:
SELECT logID, @lastuser:=user AS user, time
FROM mytable, (SELECT @lastuser:=NULL) init
HAVING NOT @lastuser<=>user
ORDER BY time DESC
See it on sqlfiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With