I have two tables, one with devices and on with corresponding service times. Each device can have several services. I’m looking for devices which last service is older than 3 Months. I tried this, which of course didn’t work:
SELECT devices.id,
devices.name,
services.servicetime
FROM devices
LEFT JOIN services
ON services.device_id = devices.id
WHERE MAX(services.servicetime) < DATE_SUB(NOW(), INTERVAL 3 MONTH);
How con i get the desired result?
Add
GROUP BY devices.idto your query, and change the condition to aHAVINGclause (evaluated after grouping). You want theMAX(services.servicetime)per device, where your current result set includes one row per service.If you want to include devices that have never been serviced, then add
OR MAX(services.servicetime) IS NULLto the end.