I am trying to update a table in MySql (Client table status field) based on the last date that this client was visited (field dateTable of the Schedule table), passing as a parameter the number of days that will define the change of the status of the same field (days field of the Customer table).
But the same customer has several visits, and I would need to check the most recent one, and based on this last visit, count the number of days the client is not visited.
I can get through SELECT all the clients and their most up-to-date dates, but I can not update them since I can not compare the most recent date (A.dataAgendada) with a list of dates.
I have tried to use LIMIT 1, but it returns only the first element of the entire query, not the first element (most recent date) of each client.
Could anyone help me?
UPDATE Cliente C INNER JOIN Agendamento A ON C.idCliente = A.idCliente
SET C.status = 'Alerta'
WHERE DATEDIFF(now(), A.dataAgendada) >= C.diasAtencao
AND A.dataAgendada = (
SELECT A.dataAgendada FROM(
SELECT MAX(Ag.dataAgendada) as agg FROM CLIENTE Cli INNER JOIN AGENDAMENTO Ag ON Cli.IDCLIENTE = Ag.IDCLIENTE
GROUP BY Cli.idCliente
ORDER BY Ag.dataAgendada DESC
) as Consulta
);