MySQL GROUP by optimization

Source: Internet
Author: User

Mysql>ExplainSelectActor.first_name,actor.last_name,Count(*) fromSakila.film_actorInner JoinSakila.actor using (actor_id)Group  byfilm_actor.actor_id\g*************************** 1. Row***************************ID:1Select_type:simpleTable: Actor Type: AllPossible_keys:PRIMARY          Key:NULLKey_len:NULLRef:NULLrows: $extra:usingTemporary; Using Filesort*************************** 2. Row***************************ID:1Select_type:simpleTable: Film_actor Type:refpossible_keys:PRIMARY, idx_fk_film_idKey:PRIMARYKey_len:2ref:sakila.actor.actor_id rows:1extra:usingIndex2Rowsinch Set(0.00sec) MySQL> 

From explain, the above notation uses temporary tables and file sorting

After rewriting

Mysql>ExplainSelectActor.first_name,actor.last_name,c.cnt fromSakila.actorInner Join(SelectACTOR_ID,Count(*) asCnt fromSakila.film_actorGroup  byACTOR_ID) asc using (actor_id) \g*************************** 1. Row***************************ID:1Select_type:PRIMARY        Table: Actor Type: AllPossible_keys:PRIMARY          Key:NULLKey_len:NULLRef:NULLrows: $Extra:NULL*************************** 2. Row***************************ID:1Select_type:PRIMARY        Table:<Derived2>Type:refpossible_keys:<Auto_key0>          Key:<Auto_key0>Key_len:2ref:sakila.actor.actor_id rows: -Extra:NULL*************************** 3. Row***************************ID:2select_type:derivedTable: Film_actor Type:IndexPossible_keys:PRIMARY, idx_fk_film_idKey:PRIMARYKey_len:4Ref:NULLrows:5462extra:usingIndex3Rowsinch Set(0.00sec) MySQL> 

If it is a subquery with filter conditions, the query filter should be added to the subquery condition as much as possible, not to the outside

MySQL GROUP by optimization

Related Article

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.