SQL - 如何获取同一创建日期的最新数据

SQL - How to get newest data of same date created

我有 table 张带有上传日期字段的图片。如果同一天上传了 2 张或更多图片,我如何获取最新的图片。

1.We 检查小时、分钟或秒。

2.If和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    |
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

要获取给定日期具有最大时间戳的所有行,请使用

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,则上述查询可以扩展为以下内容。

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

使用 ORDER BYLIMIT 怎么样?

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

ORDER by 按创建顺序对图像进行排序,然后是 ID。限制 select 只有 1 张。这应该 select 只有最新的照片。