获取具有最新日期时间而非id的每个组的id的最新记录-mysql

时间:2019-12-20 11:29:48

标签: mysql sql date

  • 我的要求是获取基于最新帧的ID(基于日期时间)并按车辆ID分组插入。

enter image description here

enter image description here

我尝试了以下查询

 select a.id,a.vehicle_id,a.info_datetime 
  from table_name a 
  join (select id, max(info_datetime) as maxdt from table_name group by vehicle_id) as b 
    on a.info_datetime = b.maxdt
  • 输出不会提供正确的ID。
  • 所以,我要插入由vehicle_id分组的最新帧的ID。
  • Max(id)或Max(info_datetime)查询不会给出准确的结果。

3 个答案:

答案 0 :(得分:1)

$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) );
echo $image[0];

答案 1 :(得分:0)

您的尝试即将到来,但是您也需要通过id加入:

select a.id,a.vehicle_id,a.info_datetime 
from table_name a 
join (
    select vehicle_id, max(info_datetime) as maxdt from table_name group by vehicle_id
) as b on a.info_datetime = b.maxdt and a.vehicle_id = b.vehicle_id

另一种方法是使用相关子查询进行过滤:

select a.*
from table_name a
where a.info_datetime = (
    select max(b.info_datetime) from table_name b where b.vehicle_id = a.vehicle_id 
)

答案 2 :(得分:0)

  • 最后得到了上面的解决方案。
SELECT id, vehicle_id, info_datetime
FROM table_name
WHERE id in (
    select max(m2.id) from table_name m2 group by m2.vehicle_id)
ORDER BY vehicle_id asc,info_datetime DESC
  • 在大约25个lac记录中执行大约需要2到3秒。