我有一个包含多个时间戳条目的表,我正在尝试列出与每个唯一bookID
条目的最新更新时间戳相关联的数据。
该表格如下:
create table rankHistory (
id int(10),
rankUpdated timestamp,
bookId varchar(10),
currentRank int(5)
);
示例数据:
INSERT INTO rankHistory
(`id`, `rankUpdated`, `bookId`,`currentRank`)
VALUES
(1, '2016-05-27 05:11:44', 'BK-001','100'),
(2, '2016-05-28 08:11:44', 'BK-001','95'),
(3, '2016-05-29 07:11:44', 'BK-001','11'),
(4, '2016-05-29 08:11:44', 'BK-001','5'),
(5, '2016-05-27 05:11:44', 'BK-002','100'),
(6, '2016-05-27 05:11:44', 'BK-002','100'),
(7, '2016-05-29 05:11:44', 'BK-002','100'),
(8, '2016-05-29 06:11:44', 'BK-002','55')
;
合并以下sqlFiddle中的示例: http://sqlfiddle.com/#!9/4b02d3/4
我正在尝试输出如下:
2016-05-29 08:11:44, BK-001, 5
2016-05-29 06:11:44, BK-002, 55
我试过并且认为可以使用的查询(我对mySQL不是很熟悉所以请温柔......)
select bookId,currentRank,MAX(rankUpdated) FROM rankHistory group by bookId
这确实显示了最新的时间戳条目,但没有显示匹配的数据。实现上述输出的正确方法是什么?
答案 0 :(得分:2)
您可以使用NOT EXISTS()
选择仅记录的记录,其中包含较新时间戳的其他记录不存在。
SELECT * FROM rankHistory t
WHERE NOT EXISTS(SELECT 1 FROM rankHistory s
WHERE s.bookId = t.bookId AND
s.rankUpdated > t.rankUpdated)
答案 1 :(得分:2)
尝试以下查询:
select Max(RankUpdated),A.bookId,A.CurrentRank from (
select bookId,currentRank,RankUpdated FROM rankHistory
where RankUpdated IN (select MAX(rankUpdated) FROM rankHistory group by CurrentRank)
group by bookId,currentRank) A
group by A.bookId
它将提供如下所需的输出: -
RankUpdated bookId currentRank
2016-05-29 08:11:44 BK-001 5
2016-05-29 06:11:44 BK-002 55
答案 2 :(得分:1)
这将有效:
select r.bookId, r.currentRank, r.rankUpdated from rankHistory r
inner join (
select id, bookId, MAX(currentRank) from (
select id, bookId, currentRank from rankHistory
order by rankUpdated desc
) t group by t.bookId
) t on t.id = r.id
答案 3 :(得分:0)
使用join
:
select a.bookId,a.currentRank,a.rankUpdated from rankHistory a join (
select bookId,MAX(rankUpdated) as maxrank FROM rankHistory group by bookId) b on a.bookID = b.bookId and a.rankUpdated=b.maxrank