一尘不染

MySQL查询,MAX()+ GROUP BY

mysql

愚蠢的SQL问题。我有一个这样的表(“ pid”是自动递增的主列)

CREATE TABLE theTable (
    `pid` INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `cost` INT UNSIGNED NOT NULL,
    `rid` INT NOT NULL,
) Engine=InnoDB;

实际表数据:

INSERT INTO theTable (`pid`, `timestamp`, `cost`, `rid`)
VALUES
  (1, '2011-04-14 01:05:07', 1122, 1),
  (2, '2011-04-14 00:05:07', 2233, 1),
  (3, '2011-04-14 01:05:41', 4455, 2),
  (4, '2011-04-14 01:01:11', 5566, 2),
  (5, '2011-04-14 01:06:06', 345, 1),
  (6, '2011-04-13 22:06:06', 543, 2),
  (7, '2011-04-14 01:14:14', 5435, 3),
  (8, '2011-04-14 01:10:13', 6767, 3)
;

我想获取每个rid的最新行的PID(每个唯一的RID 1个结果)。对于样本数据,我想:

pid | MAX(timestamp)      | rid
-----------------------------------
5   | 2011-04-14 01:06:06 | 1
3   | 2011-04-14 01:05:41 | 2
7   | 2011-04-14 01:14:14 | 3

我尝试运行以下查询:

SELECT MAX(timestamp),rid,pid FROM theTable GROUP BY rid

我得到:

max(timestamp)     ; rid; pid
----------------------------
2011-04-14 01:06:06; 1  ; 1
2011-04-14 01:05:41; 2  ; 3
2011-04-14 01:14:14; 3  ; 7

返回的PID始终是RID的PID的首次出现(行/ pid 1是第一次使用rid 1,行/ pid 3是第一次使用RID 2,行/ pid
7是第一次使用rid 3 )。尽管返回每个rid的最大时间戳,但pid并不是原始表中时间戳的pid。什么查询可以给我我想要的结果?


阅读 343

收藏
2020-05-17

共1个答案

一尘不染

(在PostgreSQL 9中测试过)

标识摆脱和时间戳。

select rid, max(timestamp) as ts
from test
group by rid;

1   2011-04-14 18:46:00
2   2011-04-14 14:59:00

加入吧。

select test.pid, test.cost, test.timestamp, test.rid
from test
inner join 
    (select rid, max(timestamp) as ts
    from test
    group by rid) maxt
on (test.rid = maxt.rid and test.timestamp = maxt.ts)
2020-05-17