我有一个mysql查询,我想要获取:
在单个记录中,每个记录有一个车辆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):
我可以使用GROUP BY vehicleID作为主查询,但我想保留最新的值
答案 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;
然后,您可以加入这两个表以获取其他字段。
这应该可以让您了解如何解决问题。您的示例查询具有不适合您的问题的其他表和逻辑。