当前位置:网站首页>How to create an index
How to create an index
2022-07-25 00:36:00 【Hua Weiyun】
How to create an index ?
There are three ways to create an index .
In execution CREATE TABLE Create index
CREATE TABLE user_index2 (
id INT auto_increment PRIMARY KEY,
first_name VARCHAR (16),
last_name VARCHAR (16),
id_card VARCHAR (18),
information text,
KEY name (first_name, last_name),
FULLTEXT KEY (information),
UNIQUE KEY (id_card)
);
Use ALTER TABLE Command to add index .
ALTER TABLE table_name ADD INDEX index_name (column_list);
ALTER TABLE To create a normal index 、UNIQUE Index or PRIMARY KEY Indexes .
among table_name Is the name of the table to be indexed ,column_list Indicate which columns are indexed , Multiple columns are separated by commas .
Index name index_name You can name it yourself , By default ,MySQL A name will be assigned to the first index column . in addition ,ALTER TABLE Allow multiple tables to be changed in a single statement , So you can create multiple indexes at the same time .
Use CREATE INDEX Command to create .
CREATE INDEX index_name ON table_name (column_list);
What to pay attention to when creating indexes ?
Non empty field : Column should be specified as NOT NULL, Unless you want to store NULL. stay mysql in , Columns with null values are difficult to optimize , Because they make indexes 、 Index statistics and comparison operations are more complex . You should use 0、 A special value or an empty string instead of a null value ;
Take discrete large fields :( The degree of difference between the values of variables ) The columns of are placed in front of the union index , Can pass count() Function to view the difference value of a field , The larger the return value, the more unique the value of the field, the higher the discreteness of the field ;
The smaller the index field, the better : The data storage of the database takes the page as the unit, the more data a page stores IO The greater the data obtained by the operation, the higher the efficiency .
What are the principles of indexing ?
1、 Leftmost prefix matching principle , Very important principle ,mysql It will keep matching to the right until it encounters a range query (>、<、between、like) Just stop matching , such as a = 1 and b = 2 and c > 3 and d = 4 If set up (a,b,c,d) Index of order ,d There is no index , If set up (a,b,d,c) The index of can be used ,a,b,d The order of can be adjusted at will .
2、= and in You can order , such as a = 1 and b = 2 and c = 3 establish (a,b,c) Indexes can be in any order ,mysql The query optimizer will help you optimize it into a form that the index can recognize .
3、 Try to select highly differentiated columns as indexes , The formula of discrimination is count(distinct col)/count(*), Indicates the proportion of fields that do not repeat , The larger the ratio, the fewer records we scan , The only key differentiator is 1, And some states 、 Gender fields may be differentiated in front of big data 0, Then someone might ask , What is the experience value of this ratio ? Different scenarios , It's also hard to determine , Generally need join We all need to 0.1 above , On average 1 Bar scan 10 Bar record .
4、 The index column cannot participate in the calculation , Keep the column “ clean ”, such as from_unixtime(create_time) = ’2014-05-29’ You can't use indexes , The reason is simple ,b+ All the data stored in the tree are the field values in the data table , But when searching , You need to apply functions to all elements to compare , Obviously it costs too much . So the sentence should be written as create_time = unix_timestamp(’2014-05-29’).
5、 Expand the index as much as possible , Don't create a new index . Let's say it's already in the table a The index of , Now want to add (a,b) The index of , All you need to do is change the original index .
Can index query improve query performance ?
It is usually faster to query data through index than to scan the whole table . But we also have to pay attention to the cost .
Indexes need space to store , It also needs regular maintenance , Whenever a record is added or deleted in a table or an index column is modified , The index itself will also be modified . This means that every recorded I* NSERT,DELETE,UPDATE Will pay more for this 4,5 Secondary disk I/O. Because indexes need extra storage and processing , Those unnecessary indexes will slow down the response time of queries . Using index queries does not necessarily improve query performance , Index range query (INDEX RANGE SCAN) It can be used in two cases :
Search based on a range , In general, the result set returned by a query is less than the number of records in the table 30%.
Search based on non unique index .
When not to index ( Index failure )?
1、 Use != perhaps <> Cause index to fail
2、 Index invalidation due to type inconsistency
3、 Index invalidation caused by function
Such as :
SELECT * FROM user WHERE DATE(create_time) = ‘2020-09-03’;
If you use a function in the index column , This is not indexed .
4、 Index invalidation caused by operator
SELECT * FROM user WHERE age - 1 = 20;
If you do a column (+,-,*,/,!), Then they won't be indexed .
5、OR Index invalidation caused by
SELECT * FROM user WHERE name = ‘ Zhang San ’ OR height = ‘175’;
OR Causes the index to be in a specific situation , Not all OR It's all about invalidating the index , If OR It's connected to the same field , Then the index will not fail , On the contrary, the index is invalid .
6、 Index invalidation caused by fuzzy search
SELECT * FROM user WHERE name LIKE ‘% ice ’;
When % You don't index before matching fields , Put it in the back to go .
边栏推荐
- LeetCode_6124_第一个出现两次的字母
- [help] mindspire training based on ascend910 cannot reproduce the model effect on GPU
- How to make five kinds of data structures in redis
- [mindspore] [training warning] warning when executing training code
- Why do I have to clean up data?
- Automated test series selenium three kinds of waiting for detailed explanation
- Managing databases in a hybrid cloud: eight key considerations
- Promtool Check
- Detailed usage of iperf
- 第四章 驱动子系统开发
猜你喜欢

Quartus: install cyclone 10 LP device library for quartus version 17.1

Advanced multithreading (Part 2)
![[acwing周赛复盘] 第 61 场周赛20220723](/img/8b/df2c8d516db1e7e5f2d50bcf62b2b1.png)
[acwing周赛复盘] 第 61 场周赛20220723

Implement a avatar looping control

Install software on kubernetes cluster using helm 3 package manager

js && ||
![[mindspore ascend] [running error] graph_ In mode, run the network to report an error](/img/81/9e96182be149aef221bccb63e1ce96.jpg)
[mindspore ascend] [running error] graph_ In mode, run the network to report an error

Moonpdflib Preview PDF usage record

Which automation tools can double the operation efficiency of e-commerce?
![[untitled]](/img/70/5db8a8df63a3fd593acf7f69640698.png)
[untitled]
随机推荐
Multi table query of SQL
Heap and stack in embedded development
Multi merchant mall system function disassembly Lecture 14 - platform side member level
Notes on topic brushing (XXII) -- Dynamic Planning: basic ideas and topics
The use of where condition in MySQL is not equal to! = The problem that null values are filtered out occurs when in, etc
ROS机械臂 Movelt 学习笔记3 | kinect360相机(v1)相关配置
Advanced multithreading (Part 2)
Does opengauss support using Sqlalchemy connections?
Grafana connection tdengine reports an error 535
如何创建索引
NFT chain game system development metauniverse gamefi construction
Redis6.2 SYSTEMd startup prompt redis service: Failed with result ‘protocol‘.
Codeworks round 650 (Div. 3) ABCD solution
QT learning - using database singleton to complete login matching + registration function
Pain and happiness -nio programming
Install software on kubernetes cluster using helm 3 package manager
Find the median of two numbers in the fourth question of C language deduction (three methods)
C # "learning code snippet" - recursively obtain all files under the folder
Tencent low code platform is officially open source! You can drag and drop and generate mobile phone projects and PC projects! Get private benefits
Dpdk based basic knowledge sorting-01