Do not use GROUP BY
for this. Your query is malformed and won't run in the most recent versions of MySQL (with the default settings) or almost any database.
select r.*
from r
where r.hora_fin_utc = (select max(r2.hora_fin_utc)
from reservas_tanatosalas r2
where r2.cod_tanatosala = r.cod_tanatosala
);
Think about the problem as a filtering problem, not an aggregation problem. You want to filter the data so only the most recent row shows up in the result set.
If performance is an issue, then you want an index on (cod_tanatosala, hora_fin_utc)
.
This is the your query:
This is the query:
SELECT r.cod_reserva, MAX(r.cod_tanatosala) FROM reservas_tanatosalas r
GROUP BY r.cod_tanatosala
HAVING MAX(r.hora_fin_utc)
This is saying:
- produce one row for each value of
cod_tanatosala
- return the maximum value of
cod_tanatosala
- ERROR HERE: Don't know what to do with
cod_reserva
. It is not the argument to an aggregation function or in the GROUP BY
.
The HAVING
is simply stating that MAX(r.hora_fin_utc)
is neither 0
nor NULL
. Not very useful.