初學(xué)mysql,語法尚不熟悉,寫分頁查詢時(shí),按照SqlServer的語法寫了ROW_NUMBER() OVER (),然后不出意外的報(bào)錯了。經(jīng)查,原來mysql不支持這種用法,于是本人開始了mysql分頁查詢語法大搜素,特此記錄,備忘。
limit方法在數(shù)據(jù)量少的時(shí)候性能還不錯,當(dāng)數(shù)據(jù)量過大,性能耗損嚴(yán)重,也就必須進(jìn)行優(yōu)化。下邊的優(yōu)化辦法,只適用于主鍵id自增的情況,就是根據(jù)id的大小來區(qū)分?jǐn)?shù)據(jù)范圍并實(shí)現(xiàn)順序或降序的分頁查詢。
這是順序排序分頁查詢方法:
-- 第一頁
select * from t_content
where id>=(select id from t_content order by add_time limit 1)
order by add_time limit 10;
-- 第二頁
select * from t_content
where id>=(select id from t_content order by add_time limit 10,1)
order by add_time limit 10;
-- 第三頁
select * from t_content
where id>=(select id from t_content order by add_time limit 20,1)
order by add_time limit 10;
這是倒敘排序分頁查詢方法:
-- 第一頁
select * from t_content
where id<=(select id from t_content order by add_time desc limit 1)
order by add_time desc limit 10;
-- 第二頁
select * from t_content
where id<=(select id from t_content order by add_time desc limit 10,1)
order by add_time desc limit 10;
-- 第三頁
select * from t_content
where id<=(select id from t_content order by add_time desc limit 20,1)
order by add_time desc limit 10;
注:查詢子句里的字段必須是有索引的字段,這樣才能根據(jù)索引快速查出目標(biāo)數(shù)據(jù)再進(jìn)行多條數(shù)據(jù)查詢,如果不是索引,查詢性能依然無法得到改善。