在mysql中ORDER BY keyword是用来给记录中的数据进行分类的,下面我来总结了order by语句利用索引进行优化的方法。
MySQL Order By语法
代码如下 | 复制代码 |
SELECT column_name(s) FROM table_name ORDER BY column_name |
注意:SQL语句是“字母大小写不敏感”的语句(它不区分字母的大小写),即:“ORDER BY”和“order by”是一样的。
MySQL Order By案例
下面的例子:从“Person”表中选取所有记录,并将“Age”列进行分类:
代码如下 | 复制代码 |
$con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM person ORDER BY age"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] echo " " . $row['LastName']; echo " " . $row['Age']; echo " "; } mysql_close($con); ?> |
上面的代码将输出下面的结果:
Glenn Quagmire 33
Peter Griffin 35
按照升序或者降序进行分类排列
如果你使用了“ORDER BY”关键词,所有记录将按照默认的升序进行排列(即:从1到9,从a到z)
使用“DESC”关键词可以制定所有的数据按照降序排列(即:从9到1,从z到a):
双击代码全选 123 SELECT column_name(s) FROM table_name ORDER BY column_name DESC
MySQL Order By根据两列进行分类
很多时候,我们需要同时根据两列内容(或者更多列)来对数据进行分类。当指定的列数多于一列时,仅在第一列的值完全相同时才参考第二列:
双击代码全选 123 SELECT column_name(s) FROM table_name ORDER BY column_name1, column_name2
通过索引优化来实现MySQL的ORDER BY语句优化:
1、ORDER BY的索引优化。如果一个SQL语句形如:
代码如下 | 复制代码 |
SELECT [column1],[column2],…. FROM [TABLE] ORDER BY [sort]; |
在[sort]这个栏位上建立索引就可以实现利用索引进行order by 优化。
2、WHERE + ORDER BY的索引优化,形如:
SELECT [column1],[column2],…. FROM [TABLE] WHERE [columnX] = [value] ORDER BY [sort];
建立一个联合索引(columnX,sort)来实现order by 优化。
注意:如果columnX对应多个值,如下面语句就无法利用索引来实现order by的优化
代码如下 | 复制代码 |
SELECT [column1],[column2],…. FROM [TABLE] WHERE [columnX] IN ([value1],[value2],…) ORDER BY[sort]; |
3、WHERE+ 多个字段ORDER BY
代码如下 | 复制代码 |
SELECT * FROM [table] WHERE uid=1 ORDER x,y LIMIT 0,10; |
建立索引(uid,x,y)实现order by的优化,比建立(x,y,uid)索引效果要好得多。
MySQL Order By不能使用索引来优化排序的情况
* 对不同的索引键做 ORDER BY :(key1,key2分别建立索引)
代码如下 | 复制代码 |
SELECT * FROM t1 ORDER BY key1, key2; |
* 在非连续的索引键部分上做 ORDER BY:(key_part1,key_part2建立联合索引;key2建立索引)
代码如下 | 复制代码 |
SELECT * FROM t1 WHERE key2=constant ORDER BY key_part2; |
* 同时使用了 ASC 和 DESC:(key_part1,key_part2建立联合索引)
代码如下 | 复制代码 |
SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 ASC; |
* 用于搜索记录的索引键和做 ORDER BY 的不是同一个:(key1,key2分别建立索引)
代码如下 | 复制代码 |
SELECT * FROM t1 WHERE key2=constant ORDER BY key1; |
* 如果在WHERE和ORDER BY的栏位上应用表达式(函数)时,则无法利用索引来实现order by的优化
代码如下 | 复制代码 |
SELECT * FROM t1 ORDER BY YEAR(logindate) LIMIT 0,10; |
特别提示:
>mysql一次查询只能使用一个索引。如果要对多个字段使用索引,建立复合索引。
>越小的数据类型通常更好:越小的数据类型通常在磁盘、内存和CPU缓存中都需要更少的空间,处理起来更快。
>简单的数据类型更好:整型数据比起字符,处理开销更小,因为字符串的比较更复杂。在MySQL中,应该用内置的日期和时间数据类型,而不是用字符串来存储时间;以及用整型数据类型存储IP地址。
>尽量避免NULL:应该指定列为NOT NULL,除非你想存储NULL。在MySQL中,含有空值的列很难进行查询优化,因为它们使得索引、索引的统计信息以及比较运算更加复杂。你应该用0、一个特殊的值或者一个空串代替空值。
>在ORDER BY操作中,MySQL只有在排序条件不是一个查询条件表达式的情况下才使用索引。

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor