当前位置:网站首页>MySQL index transaction
MySQL index transaction
2022-07-23 22:00:00 【Zzt.opkk】
MySQL Index transactions
1. Indexes
Index is a special kind of file , Contains a reference pointer to all records in the data table . You can index one or more columns in a table ,
And specify the type of index , Each index has its own data structure implementation .
1.1 effect
- In the database surface , data , Indexes The relationship between , Similar to that on the bookshelf The book , The content of the book , Book catalogue The relationship between .
- The function of index is similar to that of book catalogue , Can quickly locate , Retrieving data .

1.2 The underlying structure ( Basics )
The essence of indexing is to use some more complex data structures , Through this data structure, the records to be queried are organized , Thus, the speed of query can be accelerated .
In the data structure with high search efficiency, there are binary trees ( Red and black trees ,B+ Trees ), Hashtable . Which one is that ?
For the red and black trees , The basic structure is binary tree , If there are more elements , The height of the tree will increase , If the deeper the search data , This will lead to an increase in the number of comparisons in the query , Because the database needs to access the disk every time , But the reading time of the hard disk is much longer than the data processing time , The fewer times the database reads the hard disk, the better . More comparisons , Will slow down the speed .
For hash tables , His search time complexity 0(1), But we can only check the same situation , For range finding (< , > ) Or fuzzy search , There's nothing we can do .
The final answer is B+ Trees , Let's analyze B+ The structural characteristics and advantages of trees .
B+ The tree is made up of B The tree extends out , and B The tree is a N Fork tree , Its design idea is , Try to gather relevant data together , To read multiple data at once , Reduce the number of hard disk operations .
B Tree features :
- A node can hold multiple values , For example, above , The most one node holds 4 It's worth
- Unless the data is full , Otherwise, no new layer will be added . in other words ,B The tree pursues " layer " The less, the better. .
- Values in child nodes , And the value in the parent node , There is a strict size correspondence . Generally speaking , If the parent node has a It's worth , Then there is a+1 Child node . Like in the picture above , The parent node has two values (7 and 16), It corresponds to three child nodes , The first child node is less than 7 Value , The last child node is greater than 16 Value , The child node in the middle is 7 and 16 Between the value of the .
The time complexity of its search is log(N)N.
- B+ Tree structure
stay B Add several conditions on the basis of the tree
- Several values are stored on each node , At most, there are several subtrees .
- The elements of the parent node exist in the child node , Is the maximum of the child nodes ( minimum value ).
- The leaf nodes at the bottom are connected by a linked list
advantage :
- Fast query speed .
- A single node stores more data , The height of the tree is lower , All comparisons will be greatly reduced .
- All leaf nodes are connected by linked list , It is very convenient to find the range ( Because the leaf node contains the global data of the database ).
- Every data row , Just save it on the leaf node , Non leaf nodes do not have to store real data rows , Just store the indexed id that will do , At this time, the leaf node takes up less space , It is possible to cache non leaf nodes in memory .
1.3 Use scenarios
Index usage scenarios :
- Large amount of data , Often need to query , But it is often necessary to insert , Few modification operations .
- Insensitive to space , More sensitive to time .
1.4 Use
Create a primary key constraint (PRIMARY KEY), Unique constraint (UNIQUE), Foreign key constraints (FOREIGN KEY) when , The index of the corresponding column will be created automatically
- Look at the index
show index from Table name ;

- Create index
create index Index name on Table name ( Name )
Case study : Create a student table ,name Index of field
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-9VQaP7Bt-1658299536653)(C:\Users\a\AppData\Roaming\Typora\typora-user-images\image-20220716164720856.png)]](/img/66/39ed09464f221f5bea42649a53ba07.png)
- Delete index
Case study : Delete... From the student table name Index of field
drop index Index name on Table name ;
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-5qMrAlsS-1658299536655)(C:\Users\a\AppData\Roaming\Typora\typora-user-images\image-20220716164910136.png)]](/img/de/d8821e5e9e6d9fafa2b8c314aa8d86.png)
2. Business
2.1 Transaction scenario
Case study :
-- The test table
create table accout(id int, name varchar, balance int);
-- insert data
insert into accout values(1, ' Zhang San ', 1000), (2, ' Li Si ', 2000);
Now Zhang San transfers money to Li Si 500 element
-- sql sentence
update accout set balance = balance - 500 where name = ' Zhang San ';
update accout set balance = balance + 500 where name = ' Li Si ';
How to finish the first sentence sql after , There's something wrong with the database , Then Zhang San is less 500, But Li Si did not increase 500.
So how to deal with such emergencies ?
Solution : Either both of them are finished , Or none of them
notes : It's not true that none of them are implemented , But through recovery , Restore the influence of the previous operation , And this process is called ’ Roll back ’.
So how does the transaction rollback of the database do ?
Every operation in the database , There are records inside , If there is a problem in the middle of the transaction , According to the previous records , To deal with .
2.2 Use of transactions
1) Open transaction
start transaction;
2) perform sql sentence
3) Roll back or commit
rollback/commit;
notes : rollback It's all failure ,commit It's all success
So the above transfer sql You can write like this
start transaction;
update accout set balance = balance - 500 where name = ' Zhang San ';
update accout set balance = balance + 500 where name = ' Li Si ';
commit;
2.3 The basic characteristics of affairs
- Atomic Atomicity : Atomicity requires that all statements either succeed , Or not all of it , The unsuccessful part
- Consistency Uniformity : It stipulates before and after the submission of things , There can only be the state of things before submission and the state of things after submission , From one consistent state to another consistent state , There can be no intermediate process state .
- Durability persistence : When a thing is submitted , The database state has changed forever . The data has been updated to the hard disk .
- Isolation Isolation, : The isolation of things , Based on atomicity and consistency , Because things are atomized , Quantized , therefore , Things can be executed concurrently in the form of multiple atomic packages , however , Everything doesn't interfere with each other .
To solve the problems caused by concurrent transaction execution , MySQL When the database is introduced " Isolation level ", Users can choose a level suitable for their current business scenario , So what are the problems caused by concurrent transaction execution ?
- Dirty reading problem .( Read dirty data )
A business A, In the process of execution , A series of modifications have been made to the data , Before submitting to the database ( Before completing the transaction ), Another business B, Read the corresponding data , At this point B The data read are all temporary results , The follow-up may be immediately A It's changed . here B The reading behavior of is " Dirty reading ".
for instance :
I was in the exam , Answering questions , The students behind me are next to me , Secretly observe , And then put " answer " Take it away , Later, I found that the answer to this question is incorrect , I revised it again , At this time, this student saw " answer " Namely ’ Dirty data ’, The process of observation is ’ Dirty reading ’. How to solve it , I made an appointment with my classmates at a certain time before the exam , I checked , You can ’ Observe ’.
The solution is to lock the read operation , It is equivalent to reducing the degree of concurrency , Reduced efficiency , Improved isolation
- It can't be read repeatedly
Business A After submitting , Business B Just started reading ( Reading is locked ) And then in B During the execution of ,A Once again , Modified the data . here B In execution , The results of two read operations may be inconsistent .
for instance :
Modify the above example , After the appointed time, the students still observed , I revised the answer again , The final answer is inconsistent . How to solve : Don't read before the appointment ( Lock added before ), When you observe , I won't change the answer .
So the isolation is improved , Reduced concurrency , More accurate data , Reduced efficiency .
- Fantasy reading
Business B During reading , Business A It's been modified , No direct modification B Read data , But it affects B Read result set transactions B The result sets read twice are different .
This is “ Fantasy reading ” Unreal reading is equivalent to a special situation that cannot be repeated .
for instance :
It is agreed that I will not change when my classmates observe , So I went to change the answer of the multiple-choice question , Lead to different answers , How to solve : Be strict with your classmates ’ Observe ’ I can't do how to write , You can look at the questions in the back , So as to ensure that the read and write operations are strictly executed in serial ( After one execution , To execute another )
At this time, the isolation is the highest , Minimum concurrency , The data accuracy is the best , But the slowest .
MySQL Four gears are provided for us in , We are free to choose
| Restriction level | effect |
|---|---|
| read uncommitted | Concurrency is the strongest , Isolation is the weakest . |
| read committed | Only data after submission can be read , Solved the problem of dirty reading . Concurrency decreases , Isolation has increased a little . |
| repeatable read | There are restrictions on reading and writing , Solved the unrepeatable read problem . The concurrency ability is further reduced , Isolation is further increased . |
| serializable | Strict serial execution , The phantom reading problem was solved . Minimum concurrency , Highest isolation , But it's slow |
边栏推荐
- 实时监控Mysql数据库变化_进行数据同步_了解Canal_---Canal工作笔记001
- MySQL如何对SQL做prepare预处理(解决IN查询SQL预处理仅能查询出一条记录的问题)
- Redis常用命令对应到Redisson对象操作
- Uncertainty of distributed energy - wind speed test (realized by matlab code)
- How does MySQL prepare SQL (solve the problem that in query SQL preprocessing can only query one record)
- NLP field history most complete must read classic papers classification, sorting and sharing (with Chinese analysis)
- lambda學習(sort後面的Comparator的使用,collection後使用Collectors.groupingBy分組)
- JMeter performance comprehensive practice - sign in and batch sign in
- Given an array composed of numbers, realize the name whose output ID is a number and sorted from small to large
- I, AI doctoral student, online crowdfunding research topic
猜你喜欢
![[mathematical modeling summer training] location of distribution center](/img/d5/c9b4de6750a7ed080c194250629467.png)
[mathematical modeling summer training] location of distribution center

Improving performance with explicit rendering

【HiFlow】腾讯云新一代自动化助手,我用它完成了企业疫情提示(无代码)

MySQL的JDBC编程

U++ 学习笔记 控制物体Scale

Leetcode high frequency question 53. maximum subarray sum, continuous subarray with maximum sum, return its maximum sum

prime_ series_ level-1

阿里onedate分层思想

Storage structure and management disk. It's a bit like installing Win98. You need to partition and format the hard disk first

NLP field history most complete must read classic papers classification, sorting and sharing (with Chinese analysis)
随机推荐
How to completely force the killing of background unrelated processes?
Still have 1 requests outstanding when connection from slaveX/X.X.X.X:33202 is closed
欧氏聚类(API)及其单木分割
二分函数细节
Golang invalid argument to intn报错的解决
ApplicationContext introduction
Compare kernelshap and treeshap based on speed, complexity and other factors
University database creation and query practice -- database table design
05_ UE4 advanced_ Material UV scaling
Machine learning exercises -- right rate regression
Storage structure and management disk. It's a bit like installing Win98. You need to partition and format the hard disk first
Introduction to database system fifth edition after class exercises - Chapter 1 Introduction
Jmeter性能综合实战——签到及批量签到
Deep learning - NLP classic papers, courses, papers and other resources sorting and sharing
[arXiv] notes on uploading papers for the first time
Pulsar open source message queue_ Understand pulsar --- pulsar work notes 001
Euclidean clustering (API) and its single tree segmentation
王学岗视频编码————MediaCodec编解码
如何彻底强制杀死后台无关进程?
[create birthday card application]

