"Go" MySQL in statement optimization

Source: Internet
Author: User
Tags mysql in

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

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.