gis=# explain analyze SELECT AsText("way") AS geom, "ref" from ( select way, array_to_string(array(select * from unnest(array_agg(ref)) order by 1), ', ') as ref from ( select distinct on (w.way,ref) unnest(string_to_array(r.ref, ';')) as ref, w.way as way from planet_osm_line w, planet_osm_line r where (r.route='train' or r.route='railway' or r.line='rail') and (w.osm_id > 0) and (r.osm_id < 0) and ST_Within(w.way,r.way) ) lines group by way ) as routes WHERE "way" && SetSRID('BOX3D(-6506931.343860455 -4139217.955698919,-6495924.411787389 -4128211.023625853)'::box3d, 900913);