2016-08-09 31 views
0

我有一個表格,它有一個非唯一ID,id,一個狀態,status(我想要得到)以及它插入時間的時間戳,inserted。我需要選擇由id訂購的每個id的最新發生。我有以下表下令insertedMySQL選擇GROUP BY'd字段的最近出現次數

id | status | inserted 
------------------------------------ 
4 | approved | 2016-08-09 15:51:52 
5 | denied | 2016-08-09 15:52:36 
5 | pending | 2016-08-09 15:55:05 

結果我需要的是:

id | status | inserted 
------------------------------------ 
4 | approved | 2016-08-09 15:51:52 
5 | pending | 2016-08-09 15:55:05 

我有以下選擇:

SELECT * FROM table 
    GROUP BY id 
    ORDER BY inserted 

和我得到以下結果:

id | status | inserted 
------------------------------------ 
4 | approved | 2016-08-09 15:51:52 
5 | denied | 2016-08-09 15:52:36 

這個解決方案可能是一個簡單的解決方案,但是我在這個足夠長的嘗試內容上挑剔了我的大腦,比如內部選擇和什麼。任何幫助,將不勝感激。

編輯:

我不得不使用第三個選項從鏈接重複的問題讓我希望的結果(在一個與LEFT JOIN)。我想這是因爲我使用的是DATETIME類型,但我不確定。

回答

0
select t.* 
from 
    <T> t inner join 
    (select id, max(inserted) as max_inserted from <T> group by id) as m 
     on m.id = t.id and m.max_inserted = t.inserted 

select 
    id, 
    (
     select status from <T> t2 
     where t2.id = t.id and t2.inserted = max_inserted 
    ) as status, 
    max(inserted) as max_inserted 
from <T> 
group by id 

您可以嘗試搜索「MySQL的每個組最新的」或類似的東西替代方案更具體到MySQL。

0

如果您需要每個id的最新記錄,請不要使用group by。相反:

select t.* 
from table t 
where t.inserted = (select max(t2.inserted) from table t2 where t2.id = t.id);