One idea is to make a join of all the tables, making the max of each date, and then using GREATEST
to return the maximum of all the maximums:
select greatest(
coalesce(max(t2.fecha), 0),
coalesce(max(t3.fecha), 0),
coalesce(max(t4.fecha), 0)) as max_fecha
from tabla1 t1
left join tabla2 t2
on t2.fk_tabla1 = t1.id_tabla1
left join tabla3 t3
on t3.fk_tabla1 = t1.id_tabla1
left join tabla4 t4
on t4.fk_tabla1 = t1.id_tabla1
Edit
I just realized that in your query you include GROUP BY tabla1.id_tabla1
, which seems to indicate that you want the maximum date per id_tabla1
. If this is the case, simply add clause GROUP BY
to the query:
select t1.id_tabla1,
greatest(
coalesce(max(t2.fecha), 0),
coalesce(max(t3.fecha), 0),
coalesce(max(t4.fecha), 0)) as max_fecha
from tabla1 t1
left join tabla2 t2
on t2.fk_tabla1 = t1.id_tabla1
left join tabla3 t3
on t3.fk_tabla1 = t1.id_tabla1
left join tabla4 t4
on t4.fk_tabla1 = t1.id_tabla1
group by t1.id_tabla1
Issue 2
If you want to know which table the maximum value came from, it is a bit more complicated, but you can, using an expression CASE
:
select t1.id_tabla1,
greatest(
coalesce(max(t2.fecha), 0),
coalesce(max(t3.fecha), 0),
coalesce(max(t4.fecha), 0)) as max_fecha,
case when max(t2.fecha) = greatest(
coalesce(max(t2.fecha), 0),
coalesce(max(t3.fecha), 0),
coalesce(max(t4.fecha), 0))
then 'TABLA2'
when max(t3.fecha) = greatest(
coalesce(max(t2.fecha), 0),
coalesce(max(t3.fecha), 0),
coalesce(max(t4.fecha), 0))
then 'TABLA3'
when max(t4.fecha) = greatest(
coalesce(max(t2.fecha), 0),
coalesce(max(t3.fecha), 0),
coalesce(max(t4.fecha), 0))
then 'TABLA4'
end as nombre_tabla
from tabla1 t1
left join tabla2 t2
on t2.fk_tabla1 = t1.id_tabla1
left join tabla3 t3
on t3.fk_tabla1 = t1.id_tabla1
left join tabla4 t4
on t4.fk_tabla1 = t1.id_tabla1
group by t1.id_tabla1
Of course, it is possible that the maximum value is the same in more than one table. In that case, it will return one of the tables.