適合大型級別的百級以上的數據分頁:
如果少於10W的用 sql_2/sql_3即可
表1:
create table `t1`(
`id` int(11) not null auto_increment,
`title` char(200) not null,
`content` text not null,
flag tinyint(1) default '0'
);
sql_1:(慢)
sql_1 = "select id,title from t1 limit 開始行數,每頁的紀錄數";
查詢慢,因爲沒有用到索引(改進用sql_2):
sql_2:(多慢/少快)
sql_2 = "select id,title from t1 order by id desc 開始行數,每頁的紀錄數";
查詢不理想,用到了索引,但是如果數據大時,也會變慢,(改進用):
如果加上where,如:
sql_3:(多慢/少快)
sql_3 = "select id,title from t1 where flag = 1 order by id desc 開始行數,每頁的紀錄數";
此時加上 where 時,失去了索引的意義了,修改如下:
先修改數表,增加索引:(給where 的字段也加上索引,並放在索引的開始字段位置,即就是把 limit的字段放最後)
create table `t1`(
`id` int(11) not null auto_increment,
`title` char(200) not null,
`content` text not null,
`flag` tinyint(1) default '0',
primary key(`id`),
key `idx_key`(`flag`,`id`), /* 此時爲增加的索引 */
);
sql_4 = "select id,title from t1 where flag = 1 order by flag,id limit 開始行數,每頁的紀錄數";
同時可以考慮分頁的情況:(基本思路如下:)
先創建一個主表,只有 id,title,flag,
再創建一個詳細表,如 id,content,
從主表先搜索出,再從詳細表中獲取相關的具體內容
原文轉載於推酷網:http://www.tuicool.com/articles/Vri6rq