select Name, lll.Map, Time, min(lll.Timestamp), max(Type), Server, OldTime from
(
select Name, Map, Time, Timestamp, "top 1 rank" as Type, (select Time from record_race where Map = l.map and Timestamp < "{0}" order by Time limit 1) as OldTime from (select Timestamp, Name, Map, Time from record_race where Timestamp between "{0}" and "{1}") as l where Time <= (select min(Time) from record_race where Map = l.Map)
union all
select Name, Map, Time, Timestamp, "top 1 teamrank" as Type, OldTime from (select ID, (select Time from record_teamrace where Map = l.Map and ID != l.ID and Timestamp < "{0}" order by Time limit 1) as OldTime from (select distinct ID, Map, Time from record_teamrace where Timestamp between "{0}" and "{1}") as l left join (select Map, min(Time) as minTime from record_teamrace group by Map) as r on l.Map = r.Map where Time = minTime) as ll inner join record_teamrace as rr on ll.ID = rr.ID
union all
select Name, record_race.Map as Map, Time, record_race.Timestamp as Timestamp, "rank" as Type, -record_maps.Points as OldTime from record_race join record_maps on record_race.Map = record_maps.Map where record_race.Timestamp > "{0}" and record_maps.Points >= 30
union all
select Name, record_teamrace.Map as Map, Time, record_teamrace.Timestamp as Timestamp, "teamrank" as Type, -record_maps.Points as OldTime from record_teamrace join record_maps on record_teamrace.Map = record_maps.Map where record_teamrace.Timestamp > "{0}" and record_maps.Points >= 30
) as lll join record_maps on lll.Map = record_maps.Map
where lll.Map != "DontMove" and lll.Map != "Nyan Cat" group by Name, Map, Time order by lll.Timestamp;