MySQL will optimize the SQL statement, and the index will still be used after a certain number of conditions.
MySQL determines whether the index is used based on the index length and the number of conditions in the back.
In addition, if the in is followed by a subquery, the index is not used.
An article library with two tables: category and article. There are 10 categorical data in category. There are 200,000 article inside. There is a "article_category" field in article that corresponds to the "category_id" field in the category. The article table has article_category meanings in order to index. The database size is 1.3G.
Problem Description:
To execute a very common query:
Select * from Where article_category=oneorDERbyDESC5
The execution time is about 5 seconds or so.
Solution:
Build an index:
Create Index on article (article_category,article_id);
Select * from Where article_category=oneorDERbyDESC5
Reduced to 0.0027 seconds
To continue the question:
Select * from Where inch (2,3OrDERbyDESC5
It takes 11.285 seconds to execute.
Use or:
Select * from article where article_category=2or article_category=3Order bydesc 5
Execution Time: 11.0777
Solution: Avoid using in or or (or cause a sweep), use UNION ALL
Use UNION ALL:
(Select * fromArticlewhereArticle_category=2 Order byarticle_iddescLimit5)UNION All(Select * fromArticlewhereArticle_category=3 Order byarticle_iddescLimit5)OrDER byarticle_iddescLimit5
Execution Time: 0.0261
"Go" MySQL in statement optimization