mysql查询使用直接连接,成本更低,但执行时间更长

nnt7mjpx  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(286)

我试图优化下面的查询,这是大约1.5秒执行。

SELECT  id
    FROM  leads
    left join  leads_cstm  ON leads.id = leads_cstm.id_c
    WHERE  deleted=0
      and  cust_temp_id_c = 'xxxx';

***************************1. row***************************

           id: 1
  select_type: SIMPLE
        table: leads_cstm
   partitions: NULL
         type: ALL
possible_keys: PRIMARY
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 696334
     filtered: 10.00
        Extra: Using where

***************************2. row***************************

           id: 1
  select_type: SIMPLE
        table: leads
   partitions: NULL
         type: eq_ref
possible_keys: PRIMARY,idx_del_user,idx_leads_id_del
          key: PRIMARY
      key_len: 108
          ref: crmsuite.leads_cstm.id_c
         rows: 1
     filtered: 50.00
        Extra: Using where
2 rows in set, 1 warning (0.00 sec)

我尝试在leads\u cstm(id\u c,cust\u temp\u id\u c)上创建索引,但没有成功!!我也尝试过使用直接的连接,降低了成本,但是查询现在需要更多的时间来执行(3秒)。

mysql>  EXPLAIN     SELECT  id
    FROM  leads
    STRAIGHT_JOIN  leads_cstm  ON leads.id = leads_cstm.id_c
    WHERE  deleted=0
      and  cust_temp_id_c = 'xxxxx';

***************************1. row***************************

           id: 1
  select_type: SIMPLE
        table: leads
   partitions: NULL
         type: ref
possible_keys: PRIMARY,idx_del_user,idx_leads_id_del
          key: idx_del_user
      key_len: 2
          ref: const
         rows: 375820
     filtered: 100.00
        Extra: Using index

***************************2. row***************************

           id: 1
  select_type: SIMPLE
        table: leads_cstm
   partitions: NULL
         type: eq_ref
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 108
          ref: crmsuite.leads.id
         rows: 1
     filtered: 10.00
        Extra: Using where
2 rows in set, 1 warning (0.00 sec)

请说明为什么使用直接连接需要更多时间,以及如何优化此查询。
两个表都包含大约750000行。

cwxwcias

cwxwcias1#

我以为 deleted 位于表中 leads 以及 cust_temp_id_cleads_cstm .
要优化此查询,请尝试添加以下两个索引:

ALTER TABLE `leads` ADD INDEX `leads_idx_deleted_id` (`deleted`,`id`);
ALTER TABLE `leads_cstm` ADD INDEX `leads_cstm_idx_c_c` (`cust_temp_id_c`,`id_c`);

然后运行查询:

SELECT
        leads.id 
    FROM
        leads 
    LEFT JOIN
        leads_cstm 
            ON leads.id = leads_cstm.id_c 
    WHERE
        leads.deleted = 0 
        AND leads_cstm.cust_temp_id_c = 'xxxx'

相关问题