非常慢的SQL语句

时间:2010-01-18 11:56:56

标签: sql mysql

我遇到了一些SQL语句的主要问题,下面的语句给MySQL引擎带来了很大的压力,它几乎挂起了:

select c.title, c.initial, c.surname, c.labelno, c.email, br1.bookingdate
from explorer.booking_record br1
inner join explorer.client c
on c.labelno = br1.labelno
and email not like ''
where br1.bookingdate >= '2009-01-01'
and br1.bookingdate < '2009-01-31'
and c.labelno Not In (Select labelno from explorer.booking_record br2 where br2.labelno = br1.labelno and br2.bookingdate >= '2010-01-01' and br2.bookingdate < '2010-01-31')

我尝试了一些相同的变体,没有连接和两个子语句,按照文档的建议添加'order by'。实际上数据库中没有那么多记录,booking_record有~500,000条记录,客户端有~45万条。如果我让查询运行,它通常在70-80秒之后得到大约20个结果,但这会导致服务进入类似循环的状态。

非常感谢任何建议。

丹尼尔。

4 个答案:

答案 0 :(得分:2)

不喜欢而且不在这里很可能是罪魁祸首。

NOT LIKE更改为<>。您不需要任何“LIKE”行为,因为您没有使用任何通配符,因此您只需将其更改为“not equal”运算符。

接下来,您是否已经查看了执行计划并调查了您是否在可以使用索引的列上创建了索引?

答案 1 :(得分:0)

您是否已将索引放在where字段中?不知道是不是很慢,所以也许你可以避免这种说法。

答案 2 :(得分:0)

确保索引以下列:

explorer.booking_record.labelno
explorer.booking_record.bookingdate
explorer.booking_record.labelno
explorer.client.labelno
explorer.client.email

现在尝试以下查询:

select c.title, c.initial, c.surname, c.labelno, c.email, br1.bookingdate
from explorer.booking_record br1
left outer join explorer.booking_record br2 on br2.labelno = br1.labelno
    and br2.bookingdate >= '2010-01-01' and br2.bookingdate < '2010-01-31'
inner join explorer.client c on c.labelno = br1.labelno and c.email <> ''
where br1.bookingdate >= '2009-01-01'
    and br1.bookingdate < '2009-01-31'
    and br2.labelno is null

答案 3 :(得分:0)

'不在'往往会很慢。 尝试这样的事情,确保labelno在两个表中都被编入索引。

select c.title, c.initial, c.surname, c.labelno, c.email, br1.bookingdate 
from explorer.booking_record br1
inner join explorer.client c
on c.labelno = br1.labelno
and email not like ''
where br1.bookingdate >= '2009-01-01'
and br1.bookingdate < '2009-01-31'
and Not Exists (Select 1 from explorer.booking_record br2 where br2.labelno = br1.labelno and br2.bookingdate >= '2010-01-01' and br2.bookingdate < '2010-01-31')