Common situations: 1. Use functions or operations; 2. Implicit type conversion; 3. Use not equal to (!= or <>); 4. Use the LIKE operator and start with a wildcard; 5. OR condition; 6. NULL value; 7. Low index selectivity; 8. Leftmost prefix principle of compound index; 9. Optimizer decision-making; 10. FORCE INDEX and IGNORE INDEX.
Indexes in MySQL are an important tool to help optimize query performance, but in some cases, indexes may not work as expected, i.e. index " Failure".
The following are some common situations that cause MySQL index failure:
: When using functions or performing operations on indexed columns, the index usually will not take effect. For example:
SELECT * FROM users WHERE YEAR(date_column) = 2023;
Here, YEAR(date_column) invalidates the index.
2. Implicit type conversion: When implicit type conversion is involved in the query conditions, the index may not be used. For example, if a column is of type string but is queried using numbers, or vice versa.
SELECT * FROM users WHERE id = '123'; -- 假设id是整数类型
Use inequality (!= or <>): Using the inequality operator usually causes the index to fail because it requires scanning multiple values of the index.
SELECT * FROM users WHERE age != 25;
Use the LIKE operator and start with a wildcard character: When the LIKE operator is used and the pattern starts with the wildcard character %, the index will usually not take effect.
SELECT * FROM users WHERE name LIKE '%Smith%';
OR conditions: When using OR conditions, if all the columns involved are not indexed, or one of the conditions causes index failure, then the entire query may be Indexes will not be used.
SELECT * FROM users WHERE age = 25 OR name = 'John';
NULL值:如果索引列包含NULL值,并且查询条件涉及到NULL,索引可能不会生效。
SELECT * FROM users WHERE age IS NULL;
为了避免索引失效,建议:
The above is the detailed content of Several situations of mysql index failure. For more information, please follow other related articles on the PHP Chinese website!