选择MySQL左连接

时间:2020-04-01 11:24:08

标签: mysql sql

我不知道这只是一厢情愿,我的错误想法还是其他原因:

select 
f1,
f2,
f3
from f_import as a
left join e_im_com_codes on a.customer = e_im_com_codes.customer 
and a.cc8 = e_im_com_codes.Code
where e_im_com_codes.Code is null
and a.customer = 'd'
and a.hide = false;

这将导致一个计划如下:

    +----+-------------+----------------+------------+------+--------------------------------------------+----------------+---------+-------+--------+----------+----------------------------------------------------+
| id | select_type | table          | partitions | type | possible_keys                              | key            | key_len | ref   | rows   | filtered | Extra                                              |
+----+-------------+----------------+------------+------+--------------------------------------------+----------------+---------+-------+--------+----------+----------------------------------------------------+
|  1 | SIMPLE      | f_import       | NULL       | ref  | idx_cc8_import,idx_com_code                | idx_cc8_import | 768     | const | 216782 |    10.00 | Using where                                        |
|  1 | SIMPLE      | e_im_com_codes | NULL       | ALL  | e_im_com_codes_idx,e_im_com_codes_customer | NULL           | NULL    | NULL  |   1698 |    10.00 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+----------------+------------+------+--------------------------------------------+----------------+---------+-------+--------+----------+----------------------------------------------------+

但是大约需要一分钟才能运行。

有人对基于查询的优化有任何建议吗?还是我需要稍微修改数据库?

2 个答案:

答案 0 :(得分:0)

您可以改用not exists

select i.f1, i.f2, i.f3
from f_import i
where i.customer = 'd' and
      i.hide = false and
      not exists (select 1
                  from e_im_com_codes icc
                  where i.customer = icc.customer and
                        i.cc8 = icc.Code
                 );

然后为此,您希望在f_import(customer, hide)e_im_com_codes(customer, code)上建立索引

答案 1 :(得分:0)

首先,您应该在以下列上添加索引:

f_import.customer 
f_import.cc8
f_import.customer
f_import.hide

e_im_com_codes.customer
e_im_com_codes.Code

然后我看不出为什么查询速度慢的原因。