Replace MySQL index optimization and in or with union all

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.