1. Foreword:
In our lives, we export applications that can see the index effect, such as train schedules viewed at train stations, dictionary directories, etc. Their function is the function of indexes. They filter out the final desired results by continuously narrowing the scope of data to be obtained, and at the same time turn random events into sequential events, that is, we always use the same search method to lock Data (A-Z lookup of dictionary).
Life example-taking a train: I go to take a train back to my hometown. If there is no train schedule when I want to take the train, the worst result is that I have to go to every train stop to find the train I want to take; but there is With the timetable, I can quickly know where the train I want to go stops, and I can go directly there instead of going one by one to see if the train I want to go to, thus speeding up my visit. This train schedule is the index of the database.
2. Disk Principle:
This part has a lot of text and theory, and it gives me a headache just to read it. You can read it if you are interested. It doesn’t matter if you are not interested. When reading the following chapters, just remember one conclusion of this part:
Read data as much as possible [reduce the number of I/O interactions with the operating system].
Okay, if you are not interested, you can skip it and go to the next part.
The database implementation is relatively complex. The data is stored on the disk. In order to improve performance, part of the data can be read into the memory for calculation each time, because we know that the cost of accessing the disk is about 100,000 times that of accessing the memory. Or so, so a simple search tree is difficult to meet complex application scenarios. Accessing the disk was mentioned earlier, so here is a brief introduction to disk IO and pre-reading. Reading data from the disk relies on mechanical movement. The time spent each time reading data can be divided into three categories: seek time, rotation delay, and transmission time. Part,
a)·Seek time: the time required for the magnetic arm to move to the specified track, mainstream disks are generally less than 5ms; b) Rotation delay: it is the disk speed we often hear, such as a disk 7200 rpm, It means it can rotate 7200 times per minute, which means it can rotate 120 times per second, and the rotation delay is 1/120/2 = 4.17ms; c). Transmission time: refers to reading from the disk or writing data to the disk The time is generally a few tenths of a millisecond, which is negligible compared to the first two times.
(I have read a very detailed article: http://wdxtub.com/2016/04/16/thin-csapp-3/)
Then the time it takes to access a disk is a disk IO The time is approximately equal to 5+4.17 = 9ms, which sounds pretty good, but you must know that a 500-MIPS (Million Instructions Per Second) machine can execute 500 million instructions per second, because Instructions rely on the nature of electricity. In other words, 400,000 instructions can be executed in one IO execution time. The database often contains hundreds of thousands, millions or even tens of millions of data. Each time it takes 9 milliseconds, it is obviously a disaster.
So, conclusion: Reduce the number of operating system I/O interactions.
(We call the data read by IO each time a page. The specific size of data on a page depends on the operating system, usually 4k or 8k, that is, we read the data in a page. When data is collected, only one IO actually occurs)
3. What is an index:
During the use of the database system, data query is the most frequently used data operation.
The most basic query algorithm is of course linear search. It traverses the table and then matches row by row whether the row value is equal to the keyword to be searched. Its time complexity is O(n). However, algorithms with a time complexity of O(n) can also achieve good performance with small tables and lightly loaded databases. But when the data increases, the algorithm with a time complexity of O(n) is obviously bad, and the performance drops quickly.
Fortunately, the development of computer science has provided many better search algorithms, such as binary search and binary search. tree search) etc. If you do a little analysis, you will find that each search algorithm can only be applied to a specific data structure. For example, binary search requires that the retrieved data be ordered, while binary tree search can only be applied to binary search trees, but the data itself The organizational structure cannot completely satisfy various data structures (for example, it is theoretically impossible to organize both columns in order at the same time), so in addition to the data, the database system also maintains data structures that satisfy specific search algorithms. Structures reference (point to) data in some way, allowing advanced search algorithms to be implemented on these data structures. This data structure is an index.
4. MySQL’s B-Tree index (technically B+Tree)
Okay, here comes the core of this article!
In MySQL, there are four main types of indexes, namely: B-Tree index, Hash index, Fulltext index and R-Tree index. We mainly analyze B-Tree indexes. (B: balance means balance, not binary tree)
1. Detailed explanation of b+ tree data structure
The picture above is a b+tree, (under the innodb engine, it is different from the B+ structure under the myisam engine. To put it bluntly, it is the difference between clustered index and non-clustered index. For details, see:
Mysql-Clustered Index
The light blue block is called a disk block. You can see that each disk block contains several data items (shown in dark blue, range: [(M /2)-1, M-1] M is the total data) and pointers (shown in yellow). For example, disk block 1 contains data items 17 and 35, including pointers P1, P2, and P3. P1 represents disk blocks less than 17. P2 represents disk blocks between 17 and 35, and P3 represents disk blocks greater than 35. The real data exists in leaf nodes, namely 3, 5, 9, 10, 13, 15, 28, 29, 36, 60, 75, 79, 90, 99. Non-leaf nodes do not store real data (a characteristic of B+), but only data items that guide the search direction. For example, 17 and 35 do not actually exist in the data table.
##2.B+ tree search process
If it is the structure on the left, the number of I/Os is three times; if it is the linear table on the right, the number of I/Os is 6 times. It is obvious that the IO changes There are more
Mapping two conclusions:
1. The field len to be set as an index must be small;
2). When the data items of the b+ tree are composite data structures ( Multi-column index), such as (name, age, sex), b+ numbers are used to build the search tree in order from left to right.
For example, when data like (Zhang San, 20, F) is retrieved, the b+ tree will first compare the name to determine the next search direction. If the names are the same, age and sex will be compared in turn, and finally The retrieved data is obtained; but when data without name such as (20, F) comes, the b+ tree does not know which node to check next, because name is the first comparison factor when building the search tree, and it must be Search based on name first to know where to search next.
Map two conclusions:
1. The leftmost matching feature, the joint index is read from left to right

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

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

Zend Studio 13.0.1
Powerful PHP integrated development environment