SQL - 如何获取创建日期相同的最新数据
我有带上载日期字段的表格图像。如果在同一天上传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 |
若要在某一天的最大时间戳获得所有的行,可使用
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
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
可能会添加一个条件来处理max create的多行。在这种情况下,操作只需要最大ID。 –
感谢您的建议,但结果相同。记录仍然选择全部。在这里我的查询'最多选择。* FROM UP user_pictures INNER JOIN ( SELECT MAX(创建)AS最新 FROM user_pictures GROUP BY DATE(创建) )UP2 ON UP.created = UP2.latest' – TommyDo
@ vkp我已经添加了这个逻辑 –
哦......我以前没有看到这个。但我在哪里可以将table_name放入查询中? – TommyDo
用你的表名代替你所看到的任何地方 –
哦,我已经成功地运行了你的查询....但这很难适用于我的项目。我使用CakePHP构建查询。有了这个,我对我来说很难过。无论如何谢谢你的帮助。 (Y) – TommyDo