Skip to content

docs(mysql): add the order by condition to the pagination statement.#2866

Open
bengbengbalabalabeng wants to merge 1 commit into
Snailclimb:mainfrom
bengbengbalabalabeng:docs-mysql-pagination-index
Open

docs(mysql): add the order by condition to the pagination statement.#2866
bengbengbalabalabeng wants to merge 1 commit into
Snailclimb:mainfrom
bengbengbalabalabeng:docs-mysql-pagination-index

Conversation

@bengbengbalabalabeng
Copy link
Copy Markdown
Contributor

修改

  • 为分页子查询添加显示 ORDER BY 条件

测试示例:

CREATE TABLE EMPLOYEE (
  id INTEGER PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  dept VARCHAR(50) NOT NULL
);

ALTER TABLE EMPLOYEE ADD INDEX idx_dept(dept);
explain select e.id, name, dept from EMPLOYEE e inner join
( select id from EMPLOYEE limit 100, 10 ) as e2 on e.id = e2.id;

MySQL 在线测试平台

当表中出现多个二级索引(非自然顺序类型),子查询 select id from EMPLOYEE limit 100, 10 执行时,优化器发现:

  • 方案 A:扫描主键索引树去拿 id。
  • 方案 B:扫描 idx_dept 二级索引树去拿 id。

因为二级索引树通常比主键索引树更矮、更窄(占用的磁盘空间和内存更小),MySQL 优化器为了追求极致的 I/O 效率,几乎必然会选择扫描 idx_dept 索引树(在线测试平台结果也是如此)。

但是,idx_dept 索引树是按照 dept 字段的字母顺序 排序的,里面的 id 是完全无序杂乱的。这时候你拿到的前 100 个 id,其物理顺序是跟着部门名称排序的。你的分页顺序瞬间全部乱套,每次翻页都会出现严重的数据重复或遗漏。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant