我有一個包含作業狀態的日誌表。其中一列是工作名稱。有時候工作根本就不會運行,因此沒有條目。我的SQL確定哪些作業是從日誌中'丟失'。優化查詢表中不存在的條目的SQL查詢
此查詢大約需要17分鐘,這非常長。我有很多其他更復雜的東西(至少看起來更復雜),不需要很長時間。
這怎麼能優化?
-- Display missing jobs. Thats jobs that are not in job log but should be
declare @startDate datetime, @endDate datetime
declare @rangeInHours int
set @rangeInHours = -24
set @endDate = '2012-01-17 12:00:01'
set @startDate = dateadd(hour, @rangeInHours, @endDate)
declare @myTable table(name nvarchar(50))
insert into @myTable values('Activity work')
-- There are another 100 entries like this one above to add all the expected jobs
-- this is my sql to find missing jobs
select distinct i.name from @myTable i
where not exists
(select 1 from job_log j
where j.name = i.name
and j.start_date > @startDate and j.start_date < @endDate
)
order by i.name asc
通過一些線程,但找不到合適的答案,至少有一個我可以理解和實施與我有限的SQL。
你有'job_log'上的適當索引,特別是'(name,start_date)'上的覆蓋索引嗎?你可以發佈查詢計劃嗎? – 2012-01-17 18:01:31
job_log中有多少條記錄?查詢看起來很合理,就像Lieven說的那樣,我認爲這將是一個索引問題。 – Gary 2012-01-17 18:03:36