我似乎正在为此苦苦挣扎,我希望有人冷冷地为我提供一些启示。
petevents 将有多个重复的事件,但日期会不同。我只想要每个 petevent 中最新的一个。
SELECT name,
pets.id petid,
petroutineschedules.id,
petroutineschedules.eventid,
timeunit,
dateunit,
petevents.startdate
FROM pets
LEFT OUTER JOIN petroutineschedules
ON pets.id = petroutineschedules.petid
LEFT OUTER JOIN petevents
ON pets.id = petevents.petid
AND petevents.eventid = petroutineschedules.eventid
WHERE ( pets.id = 1025 )
AND ( pets.deletedat IS NULL )
GROUP BY petevents.startdate,
name,
pets.id,
petroutineschedules.id,
petroutineschedules.eventid,
timeunit,
dateunit
来自@aleroot 的更新查询
SELECT name, pets.id petid, petroutineschedules.id prsid, petroutineschedules.eventid, timeunit, dateunit, petevents.startdate, petevents.id peid
FROM
pets
LEFT OUTER JOIN
petroutineschedules ON pets.id = petroutineschedules.petid
LEFT OUTER JOIN
(
SELECT *
FROM petevents p1
WHERE p1.startdate =
(
SELECT MAX(startdate) FROM petevents p2
WHERE p1.petid = p2.petid
)
) AS petevents
ON pets.id = petevents.petid
AND petevents.eventid = petroutineschedules.eventid
WHERE (pets.id = 1025) AND (pets.deletedat IS NULL)
GROUP BY petevents.startdate , name , pets.id , petroutineschedules.id ,petroutineschedules.eventid , timeunit , dateunit
ORDER BY eventid