2016-05-30 37 views
0

我有一個表具有多個時間戳條目,我試圖列出與每個唯一bookID條目的最新更新時間戳相關聯的數據。mySQL如何正確分類這些數據?

該表由如下:

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

可以PLZ發表您預期的結果 – Ragesh

+1

'2016年5月29日8點十一分44秒,BK-001,11'一個錯字? – 1000111

+0

已經在查詢中完成了所需的編輯,它會給出所需的輸出 – Ragesh

回答

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

您可以使用NOT EXISTS()這將只選擇記錄,其中具有較新時間戳的另一記錄不存在。

SELECT * FROM rankHistory t 
WHERE NOT EXISTS(SELECT 1 FROM rankHistory s 
       WHERE s.bookId = t.bookId AND 
         s.rankUpdated > t.rankUpdated) 
+0

謝謝,這工作正常 – datether

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 

看到小提琴:http://sqlfiddle.com/#!9/4b02d3/9

+0

謝謝你的幫助! – datether

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 
+0

你需要你的幫助 – datether