当前位置:网站首页>Why does MySQL index fail? When do I use indexes?
Why does MySQL index fail? When do I use indexes?
2022-07-06 21:14:00 【Recharge the brain】
Preface
MySql What is the most important thing to ensure the query speed , Of course it's an index , I had a clear understanding of this yesterday .
Here's the thing , Just two days ago, a configuration dual data source ,postgresql and mysql. postgre It's from other companies , Then the demand is when postgre When the database connection fails , Connect to local database , Then there was a problem with this yesterday ,MySQL Execution is unusually slow , alike sql,postgre use 200 millisecond ,mysql Straight to 10 second , I was shocked , Once upon a time mysql There was suspicion !!!∑(゚Д゚ノ)ノ, After a careful look, there was no index ヽ(ー_ー)ノ.
Because at first, it was easy , Directly copy the table creation statement of others , It hasn't changed ( This behavior must be taken as a warning ), After adding the index, it is dozens of times faster , transcend postgre, And then learn from the experience , Decide to review carefully , How can you make such a low-end mistake !
What is index
It's like the catalogue of a Book , With the catalog , You don't need to , Go page by page to find what bytes want to check , But quickly locate the data you want to query through the directory , It's that simple (*ω*)
Create index
Use CREATE INDEX Create index
CREATE INDEX Create an index for an existing table , But you can't create a primary key index with this
CREATE < Index name > ON < Table name > (< Name > [< length >] [ ASC | DESC])
< Index name >
: Specify the index name . A table can create multiple indexes , But the name of each index in the table is unique .< Table name >
: Specify the name of the table to create the index .< Name >
: Specifies the name of the column to create the index . In general, you can consider the query statement in JOIN Clause and WHERE The columns that often appear in clauses are used as index columns .< length >
: optional . Specifies to use the length Characters to create the index . Using a portion of a column to create an index helps reduce the size of the index file , Save space for index columns . In some cases , Only prefixes of columns can be indexed . There is a maximum limit on the length of an index column 255 Bytes (MyISAM and InnoDB The maximum upper limit of the table is 1000 Bytes ), If the length of the index column exceeds this limit , You can only index with the prefix of the column . in addition ,BLOB or TEXT Columns of type must also be indexed with prefixes .ASC|DESC
: optional .ASC
Specifies that the index is arranged in ascending order ,DESC
Specifies that the indexes are arranged in descending order , The default isASC
.
Use ALTER TABLE Create index
This and CREATE INDEX almost , But this can create all indexes ,CREATE INDEX Is to create an index ,ALTER TABLE Is to modify the table structure at the same time , To create an index , Let's have a taste .. There may be restrictions on creating indexes , But there must be no drop in modifying the structure
ALTER TABLE TABLE_NAME // Splice the following
ADD INDEX [< Index name >] [< Index type >] (< Name >,…) # Add a normal index
ADD PRIMARY KEY [< Index type >] (< Name >,…) # Add a primary key index
ADD UNIQUE [ INDEX | KEY] [< Index name >] [< Index type >] (< Name >,…) # Add a unique index
ADD FOREIGN KEY [< Index name >] (< Name >,…) # Add a foreign key index
Use CREATE TABLE Create index
When creating database tables , Just create the index , If the index is frequently modified later , Generally, it is design , Not well designed , You must consider carefully when designing
CONSTRAINT PRIMARY KEY [ Index type ] (< Name >,…) # Create the primary key of the new table at the same time
KEY | INDEX [< Index name >] [< Index type >] (< Name >,…) # Create the index of the new table at the same time
UNIQUE [ INDEX | KEY] [< Index name >] [< Index type >] (< Name >,…) # Create a unique index of the table while creating a new table
FOREIGN KEY < Index name > < Name > # When creating a new table, create the foreign key of the table
Type of index
MySQL There are not many types of indexes , Less commonly used , Like me working for several years , Most of them use ordinary indexes ( Except for the primary key ), Others are rarely used . I do not know! , What is the most commonly used index , Welcome to leave a message (^_−)*
primary key Primary
A table can only have one primary key index , No repetition 、 It is not allowed to be NULL;
General index Normal
This is a mysql The most basic index in , No restrictions , If it is CHAR,VARCHAR type ,length It can be less than the actual length of the field ; If it is BLOB and TEXT type , Must specify length.
unique index Unique
Similar to a normal index , But it will force the value of the column to be unique , Allow null value
Full-text index Full Text
It is generally used on columns that need full-text retrieval , Retrieving long text is the best , For short text, use General index better ,
Which columns are suitable for index creation
- Often Searched On the list of , It can greatly improve the search speed
- Often used in (JOIN) On connected columns ( This problem happened yesterday , The fields connected by multiple tables are not indexed , This causes the query to be extremely slow )
- Often (>,<,=,in Etc. range query ) Use index , Because the index will sort , The specified range is continuous , It can greatly improve the query speed .
- Often group by and order by Add an index to the field of , Improve grouping , The speed of sorting .
- This one is also well known , Is in the where Add an index to the following conditions , Of course, add , Indexing has overhead , Don't add .
Which columns are not suitable for indexing
- Query few columns , If you don't query according to this column , Indexing is highly recommended .
- There are many duplicate values , Or most columns without values , It is also recommended to add , If there are many repeated values , It does not significantly improve the query speed , It will increase the cost .
- For those defined as text, image and bit Columns of data type should not be indexed . The amount of data in these columns is either quite large , Or the value is very small .
Why are these columns not recommended to be indexed , If every column is indexed , The query will not be fast
Quick query , however increase 、 Delete 、 Change The efficiency of , Will be seriously affected , Because when adding, deleting and modifying , The index needs to be maintained , Apart from that , The index also takes up a certain amount of physical space
Index failure
- Index cannot store null value
- When querying, use is null Index cannot be used , Will scan the whole table
- When querying, use not exists Index cannot be used , Will scan the whole table
- When querying, use not in Index cannot be used , Will scan the whole table
summary :not I can't go to the index , It scans the whole tableWhy can't I use null Well ?
Because the index is ordered ,null Where the value is placed in the index is a problem , Of course there are solutions , You can write empty strings directly , Or substitute a specific value null value
- It is not suitable for columns with more duplicate data
This simple explanation , Now there is a user table , There are 10000 pieces of data , Then we add an index to the gender field , Gender only male or Woman , Then all the gender data in this table are women , When searching , The database will be queried in the index first , Then go to the table to query , Because they are all women , So I scanned the whole table .
If it's not indexed , Then I will only scan the whole table , Efficiency is definitely better than the above situation .
- Fuzzy query by prefix like '%XX' perhaps like '%XX%'
This is a little bit easier to understand , If the prefix is ambiguous , I definitely need to see one by one , Then we can find the right , This situation will cause full table scanning
- If MySQL It is expected that the whole table will be faster , No index will be used
- If there is... In the condition or , as long as or One of the conditions does not create an index , No index will be used ( Because the column without index is supposed to be scanned by the whole table ), If you want to use or, And want the index to work , Then add indexes to the conditions .
- The use of functions in index columns will also invalidate the index
- Index participation in calculation will also invalidate the index
- Type implicit conversion
Suppose the type we store in the database is varchar, But when we execute the query statement , direct writing select name from user where id=123, Pay attention to this id=123,123 Has not been '' wrap up , So it is int type , under these circumstances , It also invalidates the index
- Comparing two columns will also invalidate the index
For example, there is storage in the table Math scores and Chinese achievement , We need to check Math scores be better than Students with Chinese scores , In this case, the index will not take effect , Even if both fields have indexes .
- It's not equal to comparison != <>
It's possible not to go , But not all , Generally speaking, when the proportion of query result set is relatively small , Can walk the index , The index will not be used when the proportion is large . This is related to the proportion of the result set and the population . Use Unequal Be careful when operating .
- order by Cause index to fail , Sorting will scan the whole table
That's all for this article , There is still a part of the index knowledge points that is not mentioned , The next part continues
I am participating in the recruitment of nuggets technology community creator signing program , Click the link to sign up for submission .
边栏推荐
- Tips for web development: skillfully use ThreadLocal to avoid layer by layer value transmission
- Nodejs教程之让我们用 typescript 创建你的第一个 expressjs 应用程序
- The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop
- Nodejs教程之Expressjs一篇文章快速入门
- In JS, string and array are converted to each other (II) -- the method of converting array into string
- 967- letter combination of telephone number
- Notes - detailed steps of training, testing and verification of yolo-v4-tiny source code
- 968 edit distance
- Word bag model and TF-IDF
- 什么是RDB和AOF
猜你喜欢
Chris LATTNER, the father of llvm: why should we rebuild AI infrastructure software
请问sql group by 语句问题
None of the strongest kings in the monitoring industry!
【mysql】游标的基本使用
Laravel notes - add the function of locking accounts after 5 login failures in user-defined login (improve system security)
Introduction to the use of SAP Fiori application index tool and SAP Fiori tools
[MySQL] basic use of cursor
拼多多败诉,砍价始终差0.9%一案宣判;微信内测同一手机号可注册两个账号功能;2022年度菲尔兹奖公布|极客头条
防火墙基础之外网服务器区部署和双机热备
for循环中break与continue的区别——break-完全结束循环 & continue-终止本次循环
随机推荐
Regular expression collection
3D face reconstruction: from basic knowledge to recognition / reconstruction methods!
Laravel notes - add the function of locking accounts after 5 login failures in user-defined login (improve system security)
js之遍历数组、字符串
El table table - get the row and column you click & the sort of El table and sort change, El table column and sort method & clear sort clearsort
Is this the feeling of being spoiled by bytes?
JS操作dom元素(一)——获取DOM节点的六种方式
c#使用oracle存储过程获取结果集实例
Pycharm remote execution
20220211 failure - maximum amount of data supported by mongodb
OneNote 深度评测:使用资源、插件、模版
What is the difference between procedural SQL and C language in defining variables
[MySQL] basic use of cursor
ACdreamoj1110(多重背包)
[in depth learning] pytorch 1.12 was released, officially supporting Apple M1 chip GPU acceleration and repairing many bugs
Web开发小妙招:巧用ThreadLocal规避层层传值
如何实现常见框架
[MySQL] trigger
Thinking about agile development
通过数字电视通过宽带网络取代互联网电视机顶盒应用