selec查詢 分頁查詢及優化

2021-09-26 10:23:41 字數 2789 閱讀 7204

select _column,_column from _table [where clause] [limit n][offset m]
解析:limit 子句可以被用於強制 select 語句返回指定的記錄數。limit 接受乙個或兩個數字引數。引數必須是乙個整數常量。

/*  注意:mysql資料庫中limit分頁查詢時,索引是從0開始的(0,1,2,3....)*/

#檢索記錄行 6-15   

select * from table limit 5,10
#為了檢索從某乙個偏移量到記錄集的結束所有的記錄行,可以指定第二個引數為 -1。 檢索記錄行 96-last.

select * from table limit 95,-1
limit n 等價於 limit 0,n

/*websites  表名   name alexa url country  字段*/

select * from websites; /* 查詢表所有資料 */

select name from websites; /* 查詢表字段資料 */

select * from websites where name = "廣西"; /* 查詢表字段下條件資料 */

select * from websites where name like "_o%"; /* 模糊查詢表下資料 */

select * from websites where id between "1" and "5"; /* 查詢表下字段範圍資料 */

select distinct country from websites; /* 查詢去重值 */

select * from websites where country = "cn" and alexa > 50; /*查詢表下範圍條件資料*/

select * from websites where country = "usa" or country="sh"; /* 查詢表下條件不同值 */

select * from websites order by alexa; /* 查詢表下值排序結果 */

select * from websites order by alexa desc; /* 查詢表下排序結果降序 */

select * from websites limit 2; /* 查詢表下範圍資料 */

select name as zzz from websites; /*別名查詢表下資料*/

select * from _table limit (page_number-1)*lines_perpage, lines_perpage

select * from _table limit lines_perpage offset (page_number-1)*lines_perpage

2.1 最基本的分頁方式:

select ... from ... where ... order by ... limit ...
在中小資料量的情況下,這樣的 sql 足夠用了,唯一需要注意的問題就是確保使用了索引。

舉例來說,如果實際 sql 類似下面語句,那麼在 category_id, id 兩列上建立復合索引比較好。

select * from articles where category_id = 123 order by id limit 50, 10
2.2 子查詢的分頁方式

隨著資料量的增加,頁數會越來越多,檢視後幾頁的 sql 就可能類似:

select * from articles where category_id = 123 order by id limit 10000, 10
一言以蔽之,就是越往後分頁,limit 語句的偏移量就會越大,速度也會明顯變慢。

此時,我們可以通過子查詢的方式來提高分頁效率,大致如下:

select * from articles where  id >=

(select id from articles where category_id = 123 order by id limit 10000, 1) limit 10

另外,如果需要查詢 id 不是連續的一段,最佳的方法就是先找出 id ,然後用 in 查詢

select * from table where id >= (select id from table limit 1000000, 1) limit 10  速度提公升到0.x秒
2.3 繼續優化

select * from table where id between 1000000 and 1000010比上面那句,還要再快5至10倍

為什麼會這樣呢?因為子查詢是在索引上完成的,而普通的查詢時在資料檔案上完成的,通常來說,索引檔案要比資料檔案小得多,所以操作起來也會更有效率。

實際可以利用類似策略模式的方式去處理分頁,比如判斷如果是一百頁以內,就使用最基本的分頁方式,大於一百頁,則使用子查詢的分頁方式。

分頁查詢優化

1 子查詢優化法 先找出第一條資料,然後大於等於這條資料的id就是要獲取的資料 缺點 資料必須是連續的,可以說不能有where條件,where條件會篩選資料,導致資料失去連續性。實驗下 如下 複製 mysql set profiling 1 query ok,0 rows affected 0.00...

分頁查詢優化

自己的乙個 由於單錶的資料記錄高達了一百萬條,造成資料訪問很慢,google分析的後台經常報告超時,尤其是頁碼大的頁面更是慢的不行。先讓我們熟悉下基本的sql語句,來檢視下我們將要測試表的基本資訊 use infomation schema select from tables where tabl...

mysql 分頁優化 Mysql 查詢分頁優化

全表掃瞄,速度極慢 limit 語句的查詢時間與起始記錄的位置成正比 mysql 的 limit 語句是很方便,但是對記錄很多的表並不適合直接使用 建立測試表 drop table if exists t user create table test t user id int 10 unsigne...