当前位置:网站首页>Several cases of index failure
Several cases of index failure
2022-07-01 11:06:00 【Rookie cat meow meow】
This article is just personal notes , If there is any error, please remind me
The best left prefix rule
The right side of the range query is invalid
like Index invalidation principle
Index invalidation caused by implicit conversion
Look at this watch
CREATE TABLE `test1` (
`id` int(11) NOT NULL,
`num1` int(11) NOT NULL DEFAULT '0',
`num2` varchar(11) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `num1` (`num1`),
KEY `num2` (`num2`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL test
Take a look at this group first SQL, There are four , Our test data sheet num1 yes int type ,num2 yes varchar type , But the stored data is related to the primary key id The same sequence of numbers , Both fields are indexed .
1: SELECT * FROM `test1` WHERE num1 = 10000;
2: SELECT * FROM `test1` WHERE num1 = '10000';
3: SELECT * FROM `test1` WHERE num2 = 10000;
4: SELECT * FROM `test1` WHERE num2 = '10000';
among 124 Three SQL Basically, the results are instantaneous , In about 0.001 ~ 0.005 second , With tens of millions of data, such a result can determine these three SQL The performance is basically the same . But third SQL, Many tests are basically time-consuming 4.5~4.8 Between seconds .
Why? 34 Two article SQL The efficiency difference is so big , But the same comparison 12 Two article SQL But it doesn't make any difference ? Take a look at the implementation plan , Bottom respectively 1234 strip SQL Execution plan data : You can see ,124 Three SQL Can use the index , The connection types are ref, The number of scanning lines is 1, So it's very efficient . Look at the third SQL, No index , So scan for the whole table ,rows Directly to 1000 All the , So the performance difference is so big .
Look up MySQL The discovery of related documents is caused by implicit transformation , Look at the official description :
Official documents : 12.2 Type Conversion in Expression Evaluation
When operators are used with different types of operands , Type conversion occurs to make operands compatible . Some transformations occur implicitly . for example ,MySQL It will automatically convert strings into numbers as needed , vice versa . The following rules describe how the comparison operation is converted :
- At least one of the two parameters is NULL when , The result of the comparison is NULL, The special case is to use <=> The two one. NULL When making a comparison, it will return 1, There is no need for type conversion in either case
- Both parameters are strings , Compare by string , No type conversion
- Both arguments are integers , Compare... By integers , No type conversion
- When comparing hexadecimal values with non numeric values , It will be treated as a binary string
- One parameter is TIMESTAMP or DATETIME, And the other parameter is constant , Constants are converted to timestamp
- One parameter is decimal type , If the other parameter is decimal Or an integer , Will convert integers to decimal Then compare , If the other parameter is a floating-point number , It will put decimal Convert to floating point for comparison
- In all other cases , Both parameters are converted to floating-point numbers for comparison
According to official documents , Our first 23 Two article SQL Implicit conversion has taken place , The first 2 strip SQL Query criteria for num1 = ‘10000’, On the left is int To the right of the type is the string , The first 3 strip SQL contrary , Then according to the official conversion rule No 7 strip , Both left and right sides will be converted to floating-point numbers for comparison .
First look at the 2 strip SQL:SELECT * FROMtest1WHERE num1 = ‘10000’; On the left for int type 10000, Convert to floating point number or 10000, Right string type ’10000’, Converting to floating point numbers is also 10000. The conversion results of both sides are unique , So it does not affect the use of indexes .
The first 3 strip SQL:SELECT * FROMtest1WHERE num2 = 10000; On the left is the string type ’10000’, Convert floating point number to 10000 Is the only one. , On the right int type 10000 The conversion result is also unique . however , Because on the left is the search condition ,‘10000’ go to 10000 Although it is the only , But other strings can also be converted to 10000, such as ’10000a’,‘010000’,'10000’ And so on can be converted to floating point numbers 10000, In this case , You can't use indexes .
The rules found by consulting relevant materials are as follows :
- Strings that do not begin with a number will be converted to 0. Such as ’abc’、‘a123bc’、'abc123’ Will be transformed into 0;
- String conversion starting with a number will be intercepted , Intercept from the first character to the first non numeric content . such as ’123abc’ Will be converted to 123,'012abc’ Will be converted to 012 That is to say 12,'5.3a66b78c’ Will be converted to 5.3, Others in the same way .
Analyze and summarize
Through the above test, we found that MySQL Use some features of operators :
- When the data types on the left and right sides of the operator are inconsistent , There will be implicit conversions .
- When where Implicit conversion occurs when the left side of the query operator is a numeric type , Then it has little effect on efficiency , But it is still not recommended .
- When where Implicit conversion occurs when the left side of the query operator is a character type , Then the index will be invalidated , The scanning efficiency of the whole meter is extremely low .
- When a string is converted to a numeric type , Strings that do not begin with numbers are converted to 0, A string beginning with a number will intercept the value from the first character to the first non numeric content as the conversion result .
therefore , We're writing SQL We must form good habits when we are young , What type of fields are queried , The condition to the right of the equal sign is written as the corresponding type . Especially when the query field is a string , The condition to the right of the equal sign must be caused by quotation marks to indicate that this is a string , Otherwise, it will cause index failure and trigger full table scan .
Different character sets and sorting rules lead to index invalidation
Other :
- It's best to match all values
- Don't do anything on the index ( Calculation 、 function 、 Automatically / Manual type conversion ), Otherwise, it will lead to index invalidation and turn to full table scan
explain select * from ti where b+1=5; -- The field operation cannot be indexed
- Try to use overlay index ( Query only indexed columns ( The index column is consistent with the query column )), Reduce select *
- Use... On index fields (!= perhaps < >) When judging , It will cause index invalidation and turn to full table scan
- Use... On index fields is null / is not null When judging , It will cause index invalidation and turn to full table scan
- Index fields use or when , It will cause index invalidation and turn to full table scan
边栏推荐
- escape sequence
- 我国蜂窝物联网用户已达 15.9 亿,年内有望超越移动电话用户
- No statements may be issued when any streaming result sets are open and in use on a given connection
- Infinite innovation in cloud "vision" | the 2022 Alibaba cloud live summit was officially launched
- Database experiment report (I)
- 移动硬盘驱动器读到,但不显示盘符
- Rising Stars in Plant Sciences (RSPS2022) Finalist科学演讲会(6.30晚9点)
- Database experiment report (II)
- [.net6] use ml.net+onnx pre training model to liven the classic "Huaqiang buys melons" in station B
- 全局过滤器(处理时间格式)
猜你喜欢
谷歌新论文-Minerva:用语言模型解决定量推理问题
CVPR22 |CMT:CNN和Transformer的高效结合(开源)
CVPR 2022 | Virtual Correspondence: Humans as a Cue for Extreme-View Geometry
编译调试Net6源码
CPI教程-异步接口创建及使用
[MPC] ② quadprog solves positive definite, semi positive definite and negative definite quadratic programming
Yoda unified data application -- Exploration and practice of fusion computing in ant risk scenarios
Node version manager NVM installation and switching
CVPR 2022 | self enhanced unpaired image defogging based on density and depth decomposition
个人商城二开逍遥B2C商城系统源码-可商用版/拼团拼购优惠折扣秒杀源码
随机推荐
12款大家都在用的产品管理平台
Leetcode 181 Employees exceeding the manager's income (June 29, 2022)
flutter path_ Provider: ^2.0.10 can get temporary directory
bash: ln: command not found
Error: missing revert data in call exception
[matytype] insert MathType inter line and intra line formulas in CSDN blog
Guys, how to export iceberg data to MySQL? What tools are there? Neither sqoop nor dataX
Project0: Games
Sqlachemy common operations
[MPC] ① quadratic programming problem matlab solver quadprog
[paper reading] trajectory guided control prediction for end to end autonomous driving: a simple yet strong Ba
NC | 肠道细胞和乳酸菌共同作用来防止念珠菌感染
kubernetes之ingress探索实践
y48.第三章 Kubernetes从入门到精通 -- Pod的状态和探针(二一)
Give up high paying jobs in Shenzhen and go back home
Huawei equipment is configured with large network WLAN basic services
MIT最新论文《对可解释特征的需求:动机和分类》:在机器学习模型的组成元素中建立可解释性
金融壹账通拟7月4日香港上市:2年亏近30亿 市值蒸发超90%
12 plateformes de gestion de produits utilisées par tout le monde
I'd like to know where I can open an account in Guangzhou? Is it safe to open an account online now?