<?php
$var 
=
'SELECT hne.near_excursion_id, hne.near_excursion_type, -- Cerro
 h.hill_id AS h_id, h.tipo AS h_tipo, h.name AS h_name, h.image_name AS h_image, -- Ruta/Trekking
 r.route_id AS r_id, r.name AS r_name, r.sector AS r_sector, -- Cerro de la ruta
 hh.hill_id AS rh_id, hh.tipo AS rh_tipo, hh.name AS rh_name, -- Foto principal de la ruta (si existe)
 rg.image AS r_image
FROM (hill_near_excursions AS hne)
LEFT JOIN hill AS h ON hne.near_excursion_type = 3 AND h.hill_id = hne.near_excursion_id
LEFT JOIN route AS r ON hne.near_excursion_type IN (1,2) AND r.route_id = hne.near_excursion_id
LEFT JOIN hill AS hh ON hne.near_excursion_type = 2 AND r.mountain_name = hh.hill_id
LEFT JOIN (
 SELECT
 MIN(route_gallery_id) AS main_rg_id,
 route_id
 FROM route_gallery
 WHERE is_main_image = 1
 GROUP BY route_id
 ) AS rgs ON rgs.route_id = r.route_id
LEFT JOIN route_gallery AS rg ON rg.route_gallery_id = rgs.main_rg_id
WHERE `hne`.`hill_id` =  3256'
;
?>