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

时间:2016-11-23 02:40:48

标签: php mysql sql select mariadb

我有上传日期字段的表格图片。如果在同一天上传了2张或更多图像,我怎样才能获得最新图像。

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    |

3 个答案:

答案 0 :(得分: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,则上述查询可以扩展为以下内容。

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

答案 1 :(得分: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

答案 2 :(得分:0)

如何使用ORDER BYLIMIT

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

ORDER通过create,然后ID对图像进行排序。限制仅选择1.这应该只选择最新的照片。