An article library contains two tables: category and article. There are 10 classified data entries in category. There are 0.2 million articles in articles. There is a "article_category" field in article that corresponds to the "category_id" field in category. In the article table, the article_category is defined as an index. The database size is 1.3 GB.
Problem description:
Execute a common query: Select * FROM 'Article' Where article_category = 11 order by article_id desc limit 5. The execution time is about 5 seconds.
Solution:
Create index idx_u on article (article_category, article_id );
Select * FROM 'Article' Where article_category = 11 order by article_id desc limit 5 reduced to 0.0027 seconds
Continue:
Select * FROM 'Article' Where article_category IN (2, 3) order by article_id desc limit 5 execution time takes 11.2850 seconds.
Use OR:
Select * from article
Where article_category = 2
Or article_category = 3
Order by article_id desc
Limit 5
Execution time: 11.0777
Solution: Avoid using in or (or will cause table scanning) and use union all
Use union all:
(Select * from article where article_category = 2 order by article_id desc limit 5)
Union all (select * from article where article_category = 3 order by article_id desc limit 5)
Order by article_id desc
Limit 5
Execution time: 0.0261