【数据库】优化排序&&高效分页
Jun 07, 2016 pm 04:02 PM例子: select cols from profiles where sex = M order by rating limit 10; 同时使用了order by,limit,如果没有索引会很慢。而sey的选择又很低,可以增加一些特殊的索引来做排序。例如,创建(sex,rating)索引。 即使有索引,如果用户需要翻页,并且翻
例子:
select
同时使用了order by,limit,如果没有索引会很慢。而sey的选择又很低,可以增加一些特殊的索引来做排序。例如,创建(sex,rating)索引。
即使有索引,如果用户需要翻页,并且翻页到比较靠后时查询也可能非常慢。
下面这个查询就通过order by 和limit偏移量的组合翻页到很靠后面的时候:
mysql>select
无论如何创建索引,这种查询都是个严重的问题。因为随着偏移量增多,MySQL需要花费大量的时间来扫描需要丢弃的数据。
反序列化、预先计算和缓存可能是解决这类问题的仅有策略。一个更好的办法是限制用户的翻页数量,实际对用户体验也不会有太大影响,因为用户很少会正在在乎搜索结果的第10000页数据。
优化这类索引的另一个比较好的策略就是使用延迟关联,通过使用覆盖索引查询返回需要的主键,再根据这些主键关联原表获得需要的行。这可以减少MySQL扫描那些丢弃的行数。下面这个查询显示了如何高效地使用(sex,rating)索引进行排序和分页。
mysql>select
-> select
->where x.sex = 'M' order by rating limit 100000,10
->as x using (
参考:《高性能MySQL》

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

C++ program optimization: time complexity reduction techniques

Detailed tutorial on establishing a database connection using MySQLi in PHP

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos

Best way to implement array pagination in PHP

Advanced sorting of PHP arrays: custom comparators and anonymous functions

How does Go WebSocket integrate with databases?

What are some ways to resolve inefficiencies in PHP functions?

How to handle database connections and operations using C++?
