色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

mysql多表查詢 分頁(yè),優(yōu)化mysql的limit

mysql多表查詢 分頁(yè),優(yōu)化mysql的limit?

在mysql中,通常使用limit做分頁(yè),而且經(jīng)常會(huì)跟order by 連用。在order by 上加索引有時(shí)候是很有幫助的,不然系統(tǒng)會(huì)做很多的filesort

經(jīng)常碰到的一個(gè)問(wèn)題是limit的offset太高,如:limit 100000,20,這樣系統(tǒng)會(huì)查詢100020條,然后把前面的100000條都扔掉,這是開銷很大的操作,導(dǎo)致查詢很慢。假設(shè)所有分頁(yè)的頁(yè)面訪問(wèn)頻率一樣,這樣的查詢平均掃描表的一半數(shù)據(jù)。優(yōu)化的方法,要么限制訪問(wèn)后面的頁(yè)數(shù),要么提升高偏移的查詢效率。

一個(gè)簡(jiǎn)單的優(yōu)化辦法是使用覆蓋查詢(covering index)查詢,然后再跟全行的做join操作。如:

復(fù)制代碼

代碼如下:

SQL>select * from user_order_info limit 1000000,5;

這條語(yǔ)句就可以優(yōu)化為:

復(fù)制代碼

代碼如下:

select * from user_order_info inner join (select pin from user_order_info limit 1000000,5) as lim using(pin);

SQL>explain select * from user_order_info limit 1000000,5;

+----+-------------+-----------------+------+---------------+------+---------+------+----------+-------+

id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra

+----+-------------+-----------------+------+---------------+------+---------+------+----------+-------+

1 | SIMPLE | user_order_info | ALL | NULL | NULL | NULL | NULL | 23131886

+----+-------------+-----------------+------+---------------+------+---------+------+----------+-------+

1 row in set (0.00 sec)

SQL>explain extended select * from user_order_info inner join (select pin from user_order_info limit 1000000,5) as lim using(pin);

+----+-------------+-----------------+--------+---------------+---------+---------+---------+----------+----------+-------------+

id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra

+----+-------------+-----------------+--------+---------------+---------+---------+---------+----------+----------+-------------+

1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 5 | 100.00

1 | PRIMARY | user_order_info | eq_ref | PRIMARY | PRIMARY | 42 | lim.pin | 1 | 100.00

2 | DERIVED | user_order_info | index | NULL | PRIMARY | 42 | NULL | 23131886 | 100.00 | Using index

+----+-------------+-----------------+--------+---------------+---------+---------+---------+----------+----------+-------------+

3 rows in set, 1 warning (0.66 sec)

根據(jù)兩個(gè)explain的對(duì)比,可以清晰發(fā)現(xiàn),第一個(gè)未使用索引,掃描了23131886行,第二個(gè)也掃描了同樣的行數(shù),但是使用了索引,效率提高了。這樣可以直接使用index得到數(shù)據(jù),而不去查詢表,當(dāng)找到需要的數(shù)據(jù)之后,在與全表join,獲得其他的列。