[MySQL index] How to make the fuzzy query index not invalid, and make the field can add% on both sides

When we use fuzzy query to add an index to SQL, it should be added to the right of the field, not to the left or both sides of the field, because doing so will cause all of them to be invalid, so how can we add it to both sides?

First example: the
following figure is a database table

CREATE TABLE `tbl_user`(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20) DEFAULT NULL,
`age`INT(11) DEFAULT NULL,
`email` VARCHAR(20) DEFAULT NULL,
PRIMARY KEY(`id`)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

INSERT INTO tbl_user(`name`,`age`,`email`)VALUES('1aa1',21,'[email protected]');
INSERT INTO tbl_user(`name`,`age`,`email`)VALUES('2bb2',23,'[email protected]');
INSERT INTO tbl_user(`name`,`age`,`email`)VALUES('3cc3',24,'[email protected]');
INSERT INTO tbl_user(`name`,`age`,`email`)VALUES('4dd4',26,'[email protected]');

Add indexes to the name and age fields:

CREATE INDEX idx_user_nameAge ON tbl_user(NAME,age)

Then we use explain to test:
Test 1: Query *

EXPLAIN SELECT * FROM tbl_user WHERE NAME LIKE '%aa%';

Insert picture description here
Test 2: Covering Index

EXPLAIN SELECT id,NAME,age FROM tbl_user WHERE NAME LIKE '%aa%';

Insert picture description here
Here we can see that the index is not invalid, and using some of the above three fields will not cause invalidation.
Test 3: Add other fields, here we did not add an index to email

EXPLAIN SELECT id,NAME,age,email FROM tbl_user WHERE NAME LIKE '%aa%';

Insert picture description here
We can see that the index is invalid

Therefore, to solve the fuzzy query, add% on both sides and the index is not invalid, then we need to cover the index when we query, that is, as in test 2 above, so we try to add indexes to the fields that need to be queried, and then Using a covering index will not cause the index to become invalid.

Guess you like

Origin blog.csdn.net/Pzzzz_wwy/article/details/106600213