分析SQL优化的limit分页延迟关联

这篇文章主要介绍“分析SQL优化的limit分页延迟关联”,在日常操作中,相信很多人在分析SQL优化的limit分页延迟关联问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”分析SQL优化的limit分页延迟关联”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

       MySQL分页查询最头疼的问题是偏移量非常大,比如limit 10000,20,就要检索出10020条记录,值返回最后20条,前边的10000行全部抛弃掉。对于检索字段非常多的情况下,效率更为糟糕。

 SELECT
	id,
	order_seq,
	product_id,
	user_id,
	artisan_id,
	order_price,
	real_pay,
	date_format( order_time, '%Y-%m-%d %H:%i:%s' ) order_time,
	user_address,
	STATUS,
	date_format( pay_time, '%Y-%m-%d %H:%i:%s' ) pay_time,
	user_contact,
	coupon_price,
	coupon_effect_price,
	order_over_time,
	product_price,
	product_trade_price,
	source_from,
	create_time,
	out_channel
FROM
	us_order 
WHERE
 ( source_from != 20 OR source_from IS NULL ) 
	AND out_channel = 0 
ORDER BY
	id DESC 
	LIMIT 1000000,10

       例如这个SQL,耗时110s。我们需要检索出1000010条记录,然后取最后10条,包括近20个字段,对于IO的消耗是非常大的,与此同时,因为SQL执行时间较长,CPU时间占比也较高,在并发高的情况下,很可能出现CPU打满。

       对于这个SQL本身来说,偏移量1000000我们无法改变,那我们如何减少MySQL扫描的页来提高查询速度呢?

SELECT
	id,
	order_seq,
	product_id,
	user_id,
	artisan_id,
	order_price,
	real_pay,
	date_format( order_time, '%Y-%m-%d %H:%i:%s' ) order_time,
	user_address,
	STATUS,
	date_format( pay_time, '%Y-%m-%d %H:%i:%s' ) pay_time,
	user_contact,
	coupon_price,
	coupon_effect_price,
	order_over_time,
	product_price,
	product_trade_price,
	source_from,
	create_time,
	out_channel 
FROM
	us_order 
	inner join
	(select id from us_order where ( source_from != 20 OR source_from IS NULL ) AND out_channel = 0 ORDER BY id DESC LIMIT 1000000,10) as aa using(id)
WHERE
	( source_from != 20 OR source_from IS NULL ) 
	AND out_channel = 0 	

到此,关于“分析SQL优化的limit分页延迟关联”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!