MySql中严重的SQL查询优化问题



我正在MySQL上运行一个非常繁重的查询,这需要几个小时,我希望能缩短处理时间。它看起来像这样:

insert into customers_input
select *
from 
(
   select *
   from cust_a a join cut_b b on a.id=b.id
   where a.date='2015-01-01' and a.date='2015-01-01'
) a left join
(
   select *
   from cust_c
) b on a.id=b.id;

cust_a-有8000000行,日期列只有两个不同的值,此外id列上还有一个BTREE索引

cust_b-有600000行,日期列只有两个不同的值,此外id列上的BTREE索引

cust_c-有20000行

我怀疑问题出在连接表cust_a和cust_b的子查询(a)上,原因很简单,因为自从我添加了这个子查询以来,处理时间大大增加了。

任何想法或建议都将不胜感激。

提前感谢

首先,不要使用子查询。您的查询也可以写成:

select *
from cust_a a join
     cust_b b
     on a.id = b.id and a.date = b.date
     where a.date = '2015-01-01' left join
     cust_c c
     on a.id = c.id;

此外,

  • 我纠正了一个表名中的拼写错误
  • 我修正了日期比较中的拼写错误
  • 我将bdate比较移到了on子句中
  • 我为c添加了一个别名

然后,此查询可以从索引cust_a(date, id)cust_b(id, date)cust_c(id)中受益。(cust_b索引的列可以按任意顺序排列。)

尝试该查询,看看它是否及时返回值。然后可以将insert放回。

最新更新