4

假设我有一张Connections表格[logID, user, time]

一个示例集是:

| 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

所需的查询应在用户列更改时对它进行 GROUP,并选择该用户的最后一个时间戳

| 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

我一直在玩 GROUP BY,但没有得到任何地方......

4

2 回答 2

6

一种方法是使用用户变量:

SELECT   logID, @lastuser:=user AS user, time
FROM     mytable, (SELECT @lastuser:=NULL) init
HAVING   NOT @lastuser<=>user
ORDER BY time DESC

sqlfiddle上查看。

于 2012-07-08T22:01:58.240 回答
4

假设没有这样的差距,人们可以使用...

    SELECT a.logID, a.user, a.time
      FROM Connections a
 LEFT JOIN Connections b ON b.logID = a.logID + 1
     WHERE a.user <> b.user 
        OR b.user IS NULL
  ORDER BY a.logID desc;

这是一个可以玩的小提琴。

于 2012-07-08T22:14:15.300 回答