2010-01-18 62 views
0
我在与SQL语句中的一些重大问题

,下面的语句引起如此大的压力到MySQL引擎它几乎挂起:很慢的SQL语句

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有大约50万条记录,客户端有450,000条记录。如果我让查询运行,它通常会在70-80秒后得到20个结果,但这会导致服务进入循环状态。

任何意见将不胜感激。

丹尼尔。

+0

您是否在labelno&bookingdate(或两者上都有复杂的一个)上定义了索引? – 2010-01-18 12:04:04

+0

我实际上没有对数据库本身的任何控制,所以我不能告诉你 - 我会看看它作为索引看起来是一个普通的话题在这里 – 2010-01-18 12:33:50

+0

好吧,我已经看了一下,labelno是一个索引在客户端,但在booking_record中的索引是在bookingref(实际上并未在此查询中使用) – 2010-01-18 12:41:38

回答

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 
+0

这工作完美,尽管只有booking_record.labelno需要索引这个工作 - 现在从n秒到0.14s。谢谢! – 2010-01-18 14:46:30

2

不喜欢和不喜欢这里最有可能的罪魁祸首。

NOT LIKE更改为<>。在这里你不需要任何'LIKE'行为,因为你没有使用任何通配符,所以你可以简单地将它改为'不等于'运算符。

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

+1

他已经在使用相关子查询,因为他在该子查询中引用了br1。 – 2010-01-18 12:07:15

+0

改变了这一点,但它没有什么区别,将看看索引 – 2010-01-18 12:35:40

0

你已经把索引放在where字段上了吗?不在和不喜欢被认为是缓慢的,所以也许你可以避免这种说法。

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')