MYSQL - 选择每条记录的最新日期(相关子查询)

时间:2015-11-09 03:13:31

标签: mysql correlated-subquery

我有一个mysql查询,我想要获取:

  • 使用日期的车辆的最新服务(从维修表中获得)(任何不是'无来自serviceType意味着它是服务)
  • 和最近的车辆计数器使用日期(从车辆加油表获得)

在单个记录中,每个记录有一个车辆ID。数据从2个不同的表中获得,同时在子查询中按车辆ID对它们进行分组。

SELECT 
r.vehicleCounter AS lastServiceCounter, 
vf.vehicleCounter AS currentCounter,
r.dateFinished,
r.type,
v.vehicleID
FROM vehicle AS v
LEFT JOIN (
        SELECT r.repairID,
        r.vehicleCounter,
        r.dateFinished,
        st.type,
        r.vehicleID
        FROM repair AS r
        INNER JOIN servicetype AS st 
        ON st.serviceTypeID = r.serviceTypeID

        WHERE st.type <> 'None' 
        AND r.dateFinished IN (
            SELECT MAX(dateFinished)
            FROM repair
            GROUP BY vehicleID
        )
   ) AS r  
   ON r.vehicleID = v.vehicleID
LEFT JOIN (
    SELECT vehicleCounter, vehicleID
    FROM vehiclefueling
    WHERE date IN(
        SELECT MAX(date)
        FROM vehicleFueling
        GROUP BY vehicleID
    )
) AS vf ON vf.vehicleID = v.vehicleID 

在运行此查询时,我应该只有每个ID的记录,但目前查询返回的记录具有不同的值的相同ID(检查ID 11):

returned query

我可以使用GROUP BY vehicleID作为主查询,但我想保留最新的值

1 个答案:

答案 0 :(得分:1)

我会使用相关子查询获得修复和加油ID:

select v.*,
       (select r.repairId
        from repairs r
        where r.vehicleID = v.vehicleID
        order by r.datefinished desc
        limit 1
       ) as repairid,
       (select vh.vehiclefuelingId
        from vehiclefueling vh
        where vh.vehicleID = v.vehicleID
        order by vh.date desc
        limit 1
       ) as vehiclefuelingId
from vehicle v;

然后,您可以加入这两个表以获取其他字段。

这应该可以让您了解如何解决问题。您的示例查询具有不适合您的问题的其他表和逻辑。