mysql語句寫法性能比較

update tbl_order_sub ts set ts.pay_status = 9
WHERE
ts.id = (
	select tse.order_sub_id from tbl_order_sub_expand tse
	where ts.out_order_id = '10030311646136'
	and ts.pay_status = 30
	and tse.pre_sale_order = 1
	and ts.id = tse.order_sub_id
)
索引:   ts.id , ts.out_order_id

受影響的行: 1
時間: 81.230ms sql

把ts.id = ()修改成ts.id in ()執行結果時間沒有改變 優化

update tbl_order_sub ts set ts.pay_status = 9
WHERE
ts.id in (
	select ts1.id from tbl_order_sub ts1,tbl_order_sub_expand tse
	where ts1.out_order_id = '10030311646136'
	and ts1.id = tse.order_sub_id
	and ts1.pay_status = 30
	and tse.pre_sale_order = 1
)
[Err] 1093 - You can't specify target table 'ts' for update in FROM clause
update tbl_order_sub ts set ts.pay_status = 9
WHERE
ts.out_order_id = '10030311646136'
and 
ts.id = (
	select ts.id from tbl_order_sub_expand tse
	where ts.out_order_id = '10030311646136'
	and ts.id = tse.order_sub_id
	and ts.pay_status = 30
	and tse.pre_sale_order = 1
	LIMIT 1
)
受影響的行: 1
時間: 0.034ms

where條件中每一次where查詢,都會先把子查詢執行一遍,因此若是能在子查詢外進行條件割捨就割捨。 spa


----------------------------------------------------------------------------------- code

update tbl_order_sub_expand ts 
		set ts.balance_due_date = now()
		where ts.order_sub_id = 
		( select tos.id from tbl_order_sub tos where tos.out_order_id = '10030311646136'
			and tos.id = ts.order_sub_id
			limit 1
		)
受影響的行: 1
時間: 94.329ms
執行時間爲94m,要放在程序裏面,那得嚇死人了。

這種狀況還不如先把order_sub_id的值取出來再進行update操做。在DB端若是是長鏈接,兩次得到connection也不會浪費太多的時間。 索引

----------------------------------------------------------------------------------- ci

update tbl_order_main om 
set om.prod_total_amt = 100,
om.online_pay_amount = 100
where om.id = (
	select os.order_main_id from tbl_order_sub os
	where os.order_main_id = om.id
	and os.id = '8b76d19ace50484ca6d14790b5c6f5ba'
)
耗時80s
update tbl_order_main om ,tbl_order_sub os
set om.prod_total_amt = 100,
om.online_pay_amount = 100
where os.order_main_id = om.id
	and os.id = '8b76d19ace50484ca6d14790b5c6f5ba'
可能會要給兩個表都進行加鎖操做
update tbl_order_main om 
set om.prod_total_amt = 100,
om.online_pay_amount = 100
where om.id = (
	select os.order_main_id from tbl_order_sub os
	where os.id = '8b76d19ace50484ca6d14790b5c6f5ba'
	limit 1
)
受影響的行: 0
時間: 0.001ms

減小了一個條件: get

where os.order_main_id = om.id
而正是這個條件讓sql解釋器無法跳過優化,須要每次都執行完整的sql


//exist效率怎麼樣 it

select * from tbl_order_main om
where EXISTS(
	select 1 from tbl_order_sub os
	where os.order_main_id = om.id
	and os.original_order_no is NULL
	and os.payment != 2
)
LIMIT 10
;
受影響的行: 0
時間: 0.059ms
select * from tbl_order_main om,tbl_order_sub os
where os.order_main_id = om.id
and os.original_order_no is NULL
and os.payment != 2
LIMIT 10
受影響的行: 0 時間: 0.124ms
相關文章
相關標籤/搜索