私は、600,000以上のレコードを含む1つのテーブルで複数の結合を持つストアドプロシージャを実行しています。問題は手続きが非常に遅く、実行に数分かかることがあることです。関連する表の列には索引が付けられていますが、まだ運がありません。SQL Server高速化クエリ
パフォーマンス向上のために何ができるでしょうか?クエリは以下に掲載されています。 @Joeは、あなたの質問にコメントで書いたように
おかげ
with CTE
as
(
select * from
(
select distinct c.ContactId, c.FirstName, c.LastName,
(select top 1 ce.Email from dbo.ContactEmails as ce where ce.ContactId = c.ContactId and ce.IsPrimary = 1) as Email,
comp.CompanyName, j.JobName, c.MobileNumber, c.OfficeNumber, cse.DateSent, MAX(cse.DateSent) over(partition by ce.email) as maxdate
from dbo.ContactSentEmails as cse
join dbo.ContactEmails as ce on cse.ContactId = ce.ContactId
join dbo.Contacts as c on ce.ContactId = c.ContactId
left join dbo.Jobs as j on c.JobId = j.JobId
left join dbo.Companies as comp on c.CompanyId = comp.CompanyId
join dbo.StaffProjects as sp on cse.StaffProjectId = sp.StaffProjectId
join dbo.Staff as s on sp.StaffId = s.StaffId
join dbo.Projects as p on sp.ProjectId = p.ProjectId
where (@ContactSourceId = -1 or c.ContactSourceId = @ContactSourceId)
and (@FirstName = '' OR c.FirstName LIKE '%' + @FirstName + '%')
and (@LastName = '' OR c.LastName LIKE '%' + @LastName + '%')
and (@EmailAddress = '' OR ce.Email LIKE '%' + @EmailAddress + '%')
and (@StaffId = -1 or sp.StaffId = @StaffId)
and (@ProjectId = -1 or sp.ProjectId = @ProjectId)
and (@OfficeId = -1 or p.OfficeId = @OfficeId)
and cse.DateSent between CONVERT(datetime, @startDate) and CONVERT(datetime, @endDate)
group by c.ContactId, c.FirstName, c.LastName, Email,comp.CompanyName, j.JobName, c.MobileNumber, c.OfficeNumber, cse.DateSent
) as tbContacts
)
select ContactId, FirstName, LastName, Email, CompanyName, JobName, MobileNumber, OfficeNumber from CTE where cte.DateSent = CTE.maxdate order by CTE.Email
ワイルドカードを使用しているLIKEはおそらくあなたを傷つけているでしょう。索引付けの量は、パフォーマンスを向上させません。 –
また、左(外側)ジョインに続いて(内側)ジョインがあります。これらの左結合は、テーブル順序に基づいて内部結合になります。クエリを壊さずにすべての内部結合の後に移動できるように見えます。 – billinkc