MYSQL in vs EXISTS optimization example

Source: Internet
Author: User
Tags mysql in

Article reprinted from: Http://www.jb51.net/article/53127.htm

When the data set of table B must be less than the data set of Table A, the in is better than exists, when the data set of table A is less than the data set of Table B, the exists is better than in

Optimization principle: Small table drive Large table, that is, small data sets drive large datasets.

############# principle (RBO) #####################

?
1234 select * from a where id in ( select id from b) for select id from b for select * from a Code class= "SQL keyword" >where a.id = b.id

When the data set of table B must be less than the data set of table A, in is better than exists.

?
1234 select * from a where exists ( select 1 Code class= "SQL keyword" >from b where b.id = a.id) for select * from a for select * from b where b.id = a.id

When the data set of a table is less than the data set of Table B, the exists is better than in.

Note: The ID field of table A and B should be indexed.

For example:

?
1234 /** 执行时间:0.313s **/SELECT SQL_NO_CACHE * FROM rocky_member m WHERE EXISTS (SELECT 1 FROM rocky_vip_appro a WHERE m.ID = a.user_id AND a.passed = 1);/** 执行时间:0.160s **/SELECT SQL_NO_CACHE * FROM rocky_member m WHERE m.ID in(SELECT ID FROM rocky_vip_appro WHERE passed = 1);

Not in and not exists usages are similar.

MYSQL in vs EXISTS optimization example

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.