首先,创建一个表如下,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);
我想查询出如下数据:
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
即:我想查询出每个rid下创建时间最晚的一条数据
我使用了如下sql:
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
结果明显不对
正确的SQL如下:
select theTable.pid,theTable.cost,theTable.timestamp,theTable.rid
from theTable INNER JOIN
(select rid,max(timestamp) as ts from theTable GROUP BY rid)
maxt on (theTable.rid = maxt.rid and theTable.timestamp = maxt.ts);