DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketBuiltTime`(vDate DATE) BEGIN DECLARE vDateStart DATETIME DEFAULT DATE(vDate); DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); DROP TEMPORARY TABLE IF EXISTS tmp.ticketBuiltTime; CREATE TEMPORARY TABLE tmp.ticketBuiltTime ENGINE = MEMORY SELECT t.id as ticketFk ,t.shipped, IFNULL(builtTime, vDateEnd) as builtTime FROM vn.ticket t LEFT JOIN ( SELECT ticketFk, builtTime FROM ( SELECT ticketFk, created as builtTime FROM ticketTracking WHERE created BETWEEN vDateStart AND vDateEnd ORDER BY ticketFk, created DESC LIMIT 10000000000000000000 ) sub GROUP BY ticketFk ) sub2 ON sub2.ticketFk = t.id WHERE t.shipped BETWEEN vDate AND util.dayEnd(vDate) AND t.clientFk NOT IN (50,400,200) AND t.companyFk = 442 ; END$$ DELIMITER ;