我有一个需要7分钟才能执行的sql。它处理一年的数据,但即便如此,我觉得它需要太长时间。你有什么建议来优化吗?
select count(s.numserviciomedico) AS total
from Actos a,
pacientes p,
Historias h,
serviciosmedicos s
where p.codigo=h.codpaciente
AND p.codigo=a.codPaciente
AND p.codigo = s.codPaciente
AND h.codPaciente = a.codPaciente
AND a.codpaciente=s.codPaciente
AND h.numHistoria = a.numHistoria
AND h.numHistoria = s.numHistoria
AND a.numHistoria = s.numHistoria
AND a.numActo = s.numActo
AND h.codSeccion=a.codSeccion
and p.codcompañia ='38'
and a.codseccion ='9'
and (CAST(FLOOR(CAST(a.fecAtencion AS float)) AS datetime) >='20090101')
and (CAST(FLOOR(CAST(a.fecAtencion AS float)) AS datetime) <='20091231')
and h.modo ='Urgente'
and datename(weekday,a.fecatencion)!= 'Sabado'
and datename(weekday,a.fecatencion)!= 'Domingo'
and CAST(FLOOR(CAST(a.fecAtencion AS float)) AS datetime) NOT IN (
select fechafestiva
from diasfestivos
)
答案 0 :(得分:2)
至少......
更改此
and (CAST(FLOOR(CAST(a.fecAtencion AS float)) AS datetime) >='20090101') and (CAST(FLOOR(CAST(a.fecAtencion AS float)) AS datetime) <='20091231')
到
a.fecAtencion >= '20090101' AND a.fecAtencion < '20100101
并使用“加入”
并且
CAST(FLOOR(CAST(a.fecAtencion AS float)) AS datetime) NOT IN (select fechafestiva from diasfestivos)
..是
NOT EXISTS (SELECT * FROM diasfestivos af WHERE a.fecAtencion >= af.fechafestiva AND a.fecAtencion < af.fechafestiva + 1)
这假设diasfestivos有更少的行,并且在那里消除时间更便宜
答案 1 :(得分:1)
SQL关键字“IN”通常是替换的好选择。
而不是EXISTS (选择来自diasfestivos的fechafestiva,其中CAST(FLOOR(CAST(a.fecAtencion AS float))AS datetime)= fechafestiva)
日期时间的演变是怎么回事?