2016-11-23 284 views
1

我有帶上載日期字段的表格圖像。如果在同一天上傳2個或更多圖像,如何獲得最新圖像?SQL - 如何獲取創建日期相同的最新數據

1.我們檢查小時,分鐘或秒鐘。

2.如果H:M:S相同,則檢查插入ID的序列。

ID |  URL |   create   | 
1 | 01.jpg |  2017-02-23 10:24:41 |<<same H:M:s 
2 | 02.jpg |  2017-02-23 10:24:41 |<<same H:M:s 
3 | 03.jpg |  2017-02-23 10:50:00 |<<same H 
4 | 04.jpg |  2017-02-24 21:50:00 |<<others 
5 | 05.jpg |  2017-03-28 17:50:00 |<<others 

輸出:我想只有

3 | 03.jpg |  2017-02-23 10:50:00 |<< newer than 1, 2 
4 | 04.jpg |  2017-02-24 21:50:00 | 
5 | 05.jpg |  2017-03-28 17:50:00 | 

回答

2

若要在某一天的最大時間戳獲得所有的行,可使用

select created,max(id) maxid 
from (select t1.*,(select count(distinct created) from t 
        where created >=t1.created 
        and cast(created as date)=cast(t1.created as date)) rn 
     from t t1) x 
    where rn=1 

如果有能在最新的時間戳上綁定並且在這種情況下只需要最新的id,上面的查詢可以擴展到以下ING。

select y.maxid id,t.url,t.created 
from (
    select created,max(id) maxid 
    from (select t1.*,(select count(distinct created) from t 
         where created >=t1.created 
         and cast(created as date)=cast(t1.created as date)) rn 
      from t t1) x 
    where rn=1 
    group by created 
) y 
join t on t.id=y.maxid and t.created=y.created 
+0

哦......我以前沒有看到這個。但我在哪裏可以將table_name放入查詢中? – TommyDo

+0

用你的表名代替你所看到的任何地方 –

+0

哦,我已經成功地運行了你的查詢....但這很難適用於我的項目。我使用CakePHP構建查詢。有了這個,我對我來說很難過。無論如何謝謝你的幫助。 (Y) – TommyDo

1
SELECT t1.* 
FROM yourTable t1 
INNER JOIN 
(
    SELECT MAX(create) AS latest, MAX(ID) AS maxID 
    FROM yourTable 
    GROUP BY DATE(create) 
) t2 
    ON t1.create = t2.latest AND 
     t1.ID  = t2.maxID 
+0

可能會添加一個條件來處理max create的多行。在這種情況下,操作只需要最大ID。 –

+0

感謝您的建議,但結果相同。記錄仍然選擇全部。在這裏我的查詢'最多選擇。* FROM UP user_pictures INNER JOIN ( SELECT MAX(創建)AS最新 FROM user_pictures GROUP BY DATE(創建) )UP2 ON UP.created = UP2.latest' – TommyDo

+0

@ vkp我已經添加了這個邏輯 –

0

如何使用ORDER BYLIMIT

SELECT * 
FROM Images 
ORDER BY create DESC, ID DESC 
LIMIT 1 

該ORDER通過創建,然後ID排序圖像。限制僅選擇1.這應該只選擇最新的照片。

+0

ORDER BY只需將數據與所需的字段進行排序。它將選擇所有數據。我認爲@Tim Biegeleisen的回答是正確的。 – TommyDo

+0

我其實只是想通了,你想每天有1個記錄。 – Pachonk

+0

是的,我是:D無論如何謝謝你的回答(Y) – TommyDo