我有一个SQL查询(由LINQ to Entities生成),大致如下:
SELECT * FROM [mydb].[dbo].[employees] JOIN [mydb].[dbo].[industry] ON jobs.industryId = industry.id JOIN [mydb].[dbo].[state] ON jobs.stateId = state.id JOIN [mydb].[dbo].[positionType] ON jobs.positionTypeId = positionType.id JOIN [mydb].[dbo].[payPer] ON jobs.salaryPerId = payPer.id JOIN [mydb].[dbo].[country] ON jobs.countryId = country.id WHERE countryName = 'US' ORDER BY startDatetime
查询返回大约1200行,我认为这不是很大的数量.不幸的是,也需要〜16秒.没有ORDER BY,查询需要< 1秒. 我使用sql Server Management Studio将一个索引放在startDatetime列上,还有一个在“cityId,industryId,startDatetime,positionTypeId,payPerId,stateId”上的聚集索引(即我们在“作业”中使用的所有列) JOINs和我们使用ORDER BY的列).我已经在JOIN中使用的每个列上都有单独的索引.不幸的是,这并没有使查询更快. 我跑了一个showplan,得到:
|--Nested Loops(Inner Join,OUTER REFERENCES:([mydb].[dbo].[jobs].[cityId])) |--Nested Loops(Inner Join,OUTER REFERENCES:([mydb].[dbo].[jobs].[stateId])) | |--Nested Loops(Inner Join,OUTER REFERENCES:([mydb].[dbo].[jobs].[industryId])) | | |--Nested Loops(Inner Join,OUTER REFERENCES:([mydb].[dbo].[jobs].[positionTypeId])) | | | |--Nested Loops(Inner Join,OUTER REFERENCES:([mydb].[dbo].[jobs].[salaryPerId])) | | | | |--Sort(ORDER BY:([mydb].[dbo].[jobs].[issueDatetime] ASC)) | | | | | |--Hash Match(Inner Join,HASH:([mydb].[dbo].[currency].[id])=([mydb].[dbo].[jobs].[salaryCurrencyId])) | | | | | |--Index Scan(OBJECT:([mydb].[dbo].[currency].[IX_currency])) | | | | | |--Nested Loops(Inner Join,WHERE:([mydb].[dbo].[jobs].[countryId]=[mydb].[dbo].[country].[id])) | | | | | |--Index Seek(OBJECT:([mydb].[dbo].[country].[IX_country]),SEEK:([mydb].[dbo].[country].[countryName]='US') ORDERED FORWARD) | | | | | |--Clustered Index Scan(OBJECT:([mydb].[dbo].[jobs].[PK_jobs])) | | | | |--Clustered Index Seek(OBJECT:([mydb].[dbo].[payPer].[PK_payPer]),SEEK:([mydb].[dbo].[payPer].[id]=[mydb].[dbo].[jobs].[salaryPerId]) ORDERED FORWARD) | | | |--Clustered Index Seek(OBJECT:([mydb].[dbo].[positionType].[PK_positionType]),SEEK:([mydb].[dbo].[positionType].[id]=[mydb].[dbo].[jobs].[positionTypeId]) ORDERED FORWARD) | | |--Clustered Index Seek(OBJECT:([mydb].[dbo].[industry].[PK_industry]),SEEK:([mydb].[dbo].[industry].[id]=[mydb].[dbo].[jobs].[industryId]) ORDERED FORWARD) | |--Clustered Index Seek(OBJECT:([mydb].[dbo].[state].[PK_state]),SEEK:([mydb].[dbo].[state].[id]=[mydb].[dbo].[jobs].[stateId]) ORDERED FORWARD) |--Clustered Index Seek(OBJECT:([mydb].[dbo].[city].[PK_city]),SEEK:([mydb].[dbo].[city].[id]=[mydb].[dbo].[jobs].[cityId]) ORDERED FORWARD)
重要的一行似乎是“| –Sort(ORDER BY:([mydb].[dbo].[jobs].[issueDatetime] ASC))” – 没有提到该列的索引.