Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Group Values

Tags:

mysql

group-by

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...

like image 989
tetris11 Avatar asked Dec 26 '22 21:12

tetris11


1 Answers

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.

like image 86
eggyal Avatar answered Jan 09 '23 02:01

eggyal