简体   繁体   English

Mysql 内连接计数查询太慢

[英]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).查询很慢:(12 秒)。 I have 4 million of records in Table1 and Table 2. This is my query:我在表 1 和表 2 中有 400 万条记录。这是我的查询:

 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):这是 desc 查询命令(见 5.524.164 记录):

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表2

Which would be the best way to get count query with inner join of two tables (Table 1 --- Table2).这将是使用两个表(表 1 --- 表 2)的内部连接获取计数查询的最佳方法。 12 Seconds is very poor time for my process. 12 秒对我的过程来说是非常糟糕的时间。

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).您肯定需要为 table2 上的 Merchant_id 创建一个索引(如果您没有)。 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.您正在尝试使用“join”关键字连接表,这意味着正在应用交叉连接。 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.另一件事是,您想使用内部连接,为什么要将条件放在 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谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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