WITH t1 AS ( SELECT o.order_id, abs(TIMESTAMPDIFF(second,o.logtime,s.logtime)) as difference FROM order_log o JOIN select_log s USING(order_id) ) SELECT CAST(avg(difference) as signed) as gap FROM t1
WITH t1 AS ( SELECT o.order_id, abs(TIMESTAMPDIFF(second,o.logtime,s.logtime)) as difference FROM order_log o JOIN select_log s USING(order_id) ) SELECT CAST(avg(difference) as signed) as gap FROM t1