MySQL分頁的優化

MySQL自帶的分頁語法依據

 LIMIT [offset,]  rows 
對於MySQL自帶分頁方式的優化

創建模擬數據表以及模擬數據

-- 創建模擬數據SQL
drop table if exists student;
 
create table if not exists student
(
    student_id int not null auto_increment primary key,
    student_name varchar(50) not null
) engine = innodb default charset = utf8;
 
 
drop table if exists course;
 
create table if not exists course
(
    course_id int not null auto_increment primary key,
    course_name varchar(10) not null
) engine = innodb default charset = utf8;
 
 
drop table if exists studentcourse;
 
create table if not exists sc
(
    sc_id int not null auto_increment primary key,
    student_id int not null,
    course_id int not null,
    score int not null
) engine = innodb default charset = utf8;
 
-- 以下數據表對應的數據記錄數
--      10  course
--  70,000  student
-- 700,000  studentcourse
-- 根據以上要求準備測試數據
 
insert into course (course_id, course_name)
select null as course_id, concat('course', ID) as course_name
from information_schema.`COLLATIONS`
order by ID asc
limit 0, 10;
 
insert into student (student_id, student_name)
select null as student_id, '' as student_name
from ( 
    select 1 as column_order_id
    from information_schema.`COLUMNS`
    limit 0, 3500
) as t
    cross join (
        select 1 as collation_order_id
        from information_schema.`COLUMNS`
        limit 0, 200
    ) as t2;
     
update student
set student_name = concat('student', student_id)
where student_name = '';
 
insert into sc (sc_id, student_id, course_id, score)
select null as sc_id, t2.student_id, t.course_id, ceiling(rand()*100) as score
from course as t
    cross join student as t2;

SELECT s.* from 

Student s

INNER JOIN SC sc

on sc.s_id = s.s_id

where sc.c_id=1 and sc.score=100;
  1. 自帶的分頁查詢
SELECT s_id,sc_id,c_id,score FROM sc ORDER BY sc_id LIMIT 6000000,10;

在這裏插入圖片描述
2. 優化自帶分頁

SELECT s_id,sc_id,c_id,score FROM sc where sc_id > 6000000 ORDER BY sc_id LIMIT 0,10

在這裏插入圖片描述
可以清晰看到提升的速度還是很快的

爲了證明不是緩存的原因
連續運行N(N>2)次自帶的分頁語句:
在這裏插入圖片描述
結果表明不是因爲緩存造成的第二次查詢速度變快

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章