MySQL查询,MAX()+ GROUP BY

cod*_*nds 28 mysql sql database relational-database

Daft SQL问题.我有一个像这样的表('pid'是自动增量主col)

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;
Run Code Online (Sandbox Code Playgroud)

实际表格数据:

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)
;
Run Code Online (Sandbox Code Playgroud)

我想得到每个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
Run Code Online (Sandbox Code Playgroud)

我试过运行以下查询:

SELECT MAX(timestamp),rid,pid FROM theTable GROUP BY rid
Run Code Online (Sandbox Code Playgroud)

我得到:

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
Run Code Online (Sandbox Code Playgroud)

返回的PID始终是RID的第一次出现(行/ pid 1是第一次使用第一次使用,第一次使用RID 2时使用行/ pid 3,使用第一次使用行/ pid 7第一次使用3) ).虽然返回每个rid的最大时间戳,但pids不是原始表中时间戳的pid.什么查询会给我我正在寻找的结果?

Mik*_*ll' 52

(在PostgreSQL 9.something中测试过)

确定rid和timestamp.

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
Run Code Online (Sandbox Code Playgroud)

加入吧.

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)
Run Code Online (Sandbox Code Playgroud)

  • 因为你想要***为每个rid***(`GROUP BY rid`),以显示"***最大时间戳***"('MAX(时间戳)`)和该行,具有最大时间戳,***相关的pid***.这是你的想法陷入困境的地方.您需要一个"窗口"功能来执行此操作,或者将"JOIN"分组到分组子查询,作为Catcall的解决方案.MYSQL没有窗口函数. (2认同)
  • 更糟糕的是,MySQL不会引发错误,而是从(随机)行获取pid. (2认同)

小智 7

select *
from (
    select `pid`, `timestamp`, `cost`, `rid`
    from theTable 
    order by `timestamp` desc
) as mynewtable
group by mynewtable.`rid`
order by mynewtable.`timestamp`
Run Code Online (Sandbox Code Playgroud)

希望我帮忙!


dkr*_*etz 5

SELECT t.pid, t.cost, to.timestamp, t.rid
FROM test as t
JOIN (
    SELECT rid, max(tempstamp) AS maxtimestamp
    FROM test GROUP BY rid
) AS tmax
    ON t.pid = tmax.pid and t.timestamp = tmax.maxtimestamp
Run Code Online (Sandbox Code Playgroud)