简体   繁体   中英

Mysql inner join count query too slow

I am trying to get count query with a simple inner join sentence. I have created index for all attributes. Query is very slow: (12 seconds). I have 4 million of records in Table1 and Table 2. This is my query:

 select count(*)
 from (`mymodb`.`Table1`
     join `mymodb`.`Table2` on ((`mymodb`.`Table2`.`id` =`mymodb`.`Table1`.`id_table1`)))
 where (`mymodb`.`Table2`.`merchant_id` = 16444)
   and Table1.created_at >= '2017-12-03 16:00:19' AND  Table1.created_at <='2018-05-03 16:00:19';

This is desc query command (see 5.524.164 records):

1   SIMPLE  Table1      ALL Table12_index,Table16_index             5524164 21.38   Using where
1   SIMPLE  Table2      eq_ref  PRIMARY,idx_Table2_id-uniq,Table26_index    PRIMARY 8   mymodb.Table1.id_table1 1   50  Using where

Table2

Which would be the best way to get count query with inner join of two tables (Table 1 --- Table2). 12 Seconds is very poor time for my process.

Firstly I would suggest simplifying your query using aliases and alternative syntax to allow you to read the query better.

You will definitely need to create an index for merchant_id on table2 (if you don't have). Then you need to analyse your query. Make sure that you have a combined index for the fields that you are querying. You should get performance increase by orders of magnitude.

You are trying to join table with "join" keyword which means cross join is applying. Cross Joins usually slower than inner joins.

And the other thing as you want to use inner join why are you putting condition with where. It is also applying cross join.

Try this query:

select count(*)
 from (`mymodb`.`Table1`
     inner join `mymodb`.`Table2` on ((`mymodb`.`Table2`.`id` =`mymodb`.`Table1`.`id_table1`)))
 ON (`mymodb`.`Table2`.`merchant_id` = 16685)
   and Table1.created_at >= '2017-12-03 16:00:19' AND  Table1.created_at <='2018-05-03 16:00:19';

Hope it works.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM