select
a.*
from
`table_1` a
left join `table_2` b on a.order_id = b.id
where a.is_active = 1 and b.is_active = 1
and b.order_status not in (7,10003)
and b.order_category_type = 3
and a.estimate_arr_port_date >= '2022-05-25 00:00:00.0'
and a.estimate_arr_port_date < '2022-05-25 23:59:59.999'
ORDER BY a.created_date DESC
limit 0, 100
SELECT COUNT(0)
FROM table_1 a
LEFT JOIN table_2 b ON a.order_id = b.id
WHERE a.is_active = 1
AND b.is_active = 1
AND b.order_status NOT IN (7, 10003)
AND b.order_category_type = 3
AND a.estimate_arr_port_date >= '2022-05-27 00:00:00.0'
AND a.estimate_arr_port_date < '2022-05-27 23:59:59.999'
生产上捕获到两条慢SQL,这两条其实都差不多,所以我把它当成一个案例
尝试使用exists 优化,发现使用了DEPENDENT SUBQUERY,这显然性能恶化了。。
explain
select
count(*)
from
`fullfill_trunk_line_sea` a
left join `order` b on a.order_id = b.id
where a.is_active = 1 and b.is_active = 1
and exists(
select 1 from `order` T2 where
b.id = T2.id
and T2.order_status not in (7, 10003)
)
and b.order_category_type = 3
and a.estimate_arr_port_date >= '2022-01-25 00:00:00.0'
and a.estimate_arr_port_date < '2022-05-25 23:59:59.999'
ORDER BY a.created_date DESC
limit 0, 100;

这时候就该考虑将连表查优化成两张单表查了。。
先查出a表的记录,通过外键id集合去b表过滤。代码判断状态不匹配的。接着内存分页等。