当前位置:网站首页>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 is ASC.

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

  1. 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 table

Why 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

  1. 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 .

  1. 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

  1. If MySQL It is expected that the whole table will be faster , No index will be used
  2. 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 .
  3. The use of functions in index columns will also invalidate the index
  4. Index participation in calculation will also invalidate the index
  5. 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

  1. 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 .

  1. 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 .

  1. 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

2365E844.gif

I am participating in the recruitment of nuggets technology community creator signing program , Click the link to sign up for submission .

原网站

版权声明
本文为[Recharge the brain]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061253102732.html