当前位置:网站首页>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 |
边栏推荐
- 阿里onedate分层思想
- 启牛是什么?请问一下手机开户股票开户安全吗?
- Real time monitoring of MySQL database changes_ Synchronize data_ Learn about canal_--- Canal work notes 001
- 如何徹底强制殺死後臺無關進程?
- How to use cesium knockout?
- ADB 命令结合 monkey 的简单使用,超详细
- 众邦科技又一潜心力作 —— 陀螺匠 OA 系统
- Leaderboard design in game server
- How about opening an account for Haitong Securities? Is it safe
- Programmer growth Article 26: how to hold a good daily morning meeting?
猜你喜欢

产品生命周期,常见的项目职能,信息流 都是什么

Yushu A1 robot dog gesture control

138 - query case - knowledge points involved: foreach traversal & computed calculation attributes & V-for loop

10道面试基础笔试题,你能对几题?

PCL error: error c2589 "(": "::" illegal mark on the right)

Summary of database stress testing methods

-2021 sorting and sharing of the latest required papers related to comparative learning

Openlayers instance accessible map accessible map

University database creation and query practice -- database table design

Openlayers instance advanced view positioning advanced view positioning
随机推荐
[isprint function determines whether characters can be output]
MySQL的JDBC編程
【数学建模暑期培训】配送中心选址问题
淘宝助理停用,用大淘营导入数据包上传宝贝提示“主图为必填项,不能为空”是什么原因?如何解决?
为了一劳永逸而写的数独
Neo4j应用
Openlayers instance accessible map accessible map
MySQL的JDBC编程
How to use cesium knockout?
JS - event proxy and application scenarios
初探POC编写
U++ 事件
Apprentissage Lambda (utilisation du comparateur après tri, regroupement après collecte avec collectors.groupingby)
U++学习笔记 基础人物轴绑定及映射绑定
Pulsar open source message queue_ Understand pulsar --- pulsar work notes 001
-2021 sorting and sharing of the latest required papers related to comparative learning
What are the product life cycle, common project functions, and information flow
实验设计
众邦科技又一潜心力作 —— 陀螺匠 OA 系统
Redis common commands correspond to redisson object operations

