MySql 複雜的刪除語句很慢

delete from product_parameter where parameter_id in (
select p4.parameter_id from product p1 inner join product_parts_relation p2 on p1.product_id = p2.product_id and p1.version = p2.version
inner join product_parts_element_relation p3 on p2.parts_id = p3.parts_id
inner join product_element_parameter_relation p4 on p4.element_id = p3.element_id
where
p1.`status` = 'published' and p1.is_last_version = '1' and p1.is_inuse = '1'
and p2.parts_type = 'first_product'
and p3.element_type in ('prepayFee','prepayFeeSeg')
and p1.product_id in ('abc'));

這個SQL在幾百萬的數據量下執行超慢,看了下執行計劃,是先遍歷執行delete,每一個遍歷結果都執行一遍子查詢,總共需要執行24W+次子查詢

 

改成使用連接的方式,看執行計劃,最後才執行delete語句

delete a from product_parameter a 
inner join product_element_parameter_relation p4 on p4.parameter_id = a.parameter_id 
inner join product_parts_element_relation p3 on p4.element_id = p3.element_id
inner join product_parts_relation p2 on p2.parts_id = p3.parts_id 
inner join product p1 on p1.product_id = p2.product_id and p1.version = p2.version 
where 
p1.`status` = 'published' -- and p1.is_last_version = '1' 
and p1.is_inuse = '1'
and p2.parts_type = 'first_product' 
and p3.element_type in ('prepayFee','prepayFeeSeg')
and p1.product_id in 
('abc'); 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章