日期:2014-05-16  浏览次数:20749 次

这个臃肿的sql语句如何优化?
今天网站发生了件很奇怪的问题,页面因为查询数据库时间过长,导致查询请求过期了,直接报错.我把sql语句打印出来了,再到服务器数据库做查询,结果花费了我40s的查询时间才把结果查出来,代码如下:
select crmID from modifyHistory h1 where newValue like '%已面谈%' and (modifyTime > '2012-05-01 00:00:00' and modifyTime < '2012-05-29 23:59:59')and ((select count(1) from modifyHistory h2 where newValue like '%已面谈%' and h2.crmID = h1.crmID and h2.modifyTime < h1.modifyTime) = 0)

奇怪的是,当我把'2012-05-01 00:00:00'换成任意其他时间比如更早的'2012-04-01 00:00:00'的时候,查询的结果1s就可以获得.这个结果让我很吃惊,也找不出是任何原因.

这是一条复杂的sql查询语句,目的是:取出数据库中的客户id,这些客户必须是同时符合以下条件
1.修改记录中修改的新值包含"已面谈"字段
2.这个修改操作在我们给定的时间范围内.
3.这是第一次出现的"已面谈"

这条查询语句可否优化?如果可以,要怎么优化?麻烦高手给出优化语句.

------解决方案--------------------
创建如下索引。

create index x1 on modifyHistory(modifyTime);
create index x2 on modifyHistory(crmID,modifyTime);
------解决方案--------------------
select crmID 
from modifyHistory h1 
where newValue like '%已面谈%' 
and modifyTime between '2012-05-01' and '2012-05-29 23:59:59'
and not exists (
select 1 from modifyHistory
where newValue like '%已面谈%'
and crmID = h1.crmID 
and modifyTime < h1.modifyTime
);