SELECT IF(cpn.idc IS NULL, 0,cpn.idc) AS idcupon,CONCAT('cupones/',cuponera.imagen) AS imagen FROM cupondestacado INNER JOIN cuponera ON cupondestacado.idcuponera=cuponera.idcuponera LEFT JOIN (SELECT idconsumidor,idcuponera,MAX(idcupon) AS idc FROM cupon WHERE idestadocupon IN (2,5) GROUP BY idconsumidor,idcuponera) AS cpn ON cuponera.idcuponera=cpn.idcuponera AND cpn.idconsumidor = { ncnd}