Example of MYSQLIN and EXISTS Optimization _ MySQL

Source: Internet
Author: User
When the dataset of Table B must be smaller than the dataset of Table A, in is better than exists. when the dataset of Table A is smaller than that of Table B, exists is used to better than in optimization principle: small tables drive large tables, that is, small datasets drive large datasets.

############ Principle (RBO )#####################

Select * from A where id in (select id from B) is equivalent to: for select id from Bfor select * from A where A. id = B. id

When the dataset of Table B must be smaller than the dataset of Table A, in is better than exists.

Select * from A where exists (select 1 from B where B. id = A. id) is equivalent to for select * from Afor select * from B where B. id = A. id

When the dataset of Table A is less than the dataset of Table B, exists is better than in.

Note: the ID fields of Table A and Table B should be indexed.

For example:

/** Execution time: 0.313 s **/SELECT SQL _NO_CACHE * FROM rocky_member m WHERE EXISTS (SELECT 1 FROM rocky_vip_appro a WHERE m. ID =. user_id AND. passed = 1);/** Execution time: 0.160 s **/SELECT SQL _NO_CACHE * FROM rocky_member m WHERE m. ID in (select id from rocky_vip_appro WHERE passed = 1 );

The usage of not in and not exists is similar.

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.