2012-05-08 147 views
0

我正在使用Linq到SQl來查詢數據。當我寫一個選擇查詢與ORDER BY和SQL Server Profiler中監控運行它選擇命令2倍Linq到SQl查詢性能

  1. 從表
  2. 選擇字段對數據進行排序。

數據龐大時需要時間。有沒有解決方案。

更新:

from dc in dataContext.UserTable join 
m in dataContext.MonthLookups on dc.Month equals m.Month into sr 
from x in sr.DefaultIfEmpty() 
order by dc.UserName, dc.FirstName 
select new {dc, sr.MothName}; 

更新:

SELECT 
[Project1].[ UserName] AS [UserName], 
[Project1].[ FirstName] AS [FirstName], 
[Project1].[ MonthName] AS [MonthName], 
[Project1].[year] AS [year] 
FROM (SELECT 
    [Extent1].[UserName] AS [UserName], 
    [Extent1].[FirstName] AS [FirstName], 
    [Extent1].[year] AS [year], 
    [Extent2].[MonthName] AS [MonthName] 
    FROM [dbo].[DutySavingFin] AS [Extent1] 
    LEFT OUTER JOIN [dbo].[MonthLookup] AS [Extent2] ON [Extent1].[Month] = [Extent2].[Month] 
) AS [Project1] 
ORDER BY [Project1].[UserName] ASC, [Project1].[FirstName] ASC 

更新:

優選方式:

SELECT 
    [Extent1].[UserName] AS [UserName], 
    [Extent1].[FirstName] AS [FirstName], 
    [Extent1].[year] AS [year], 
    [Extent2].[MonthName] AS [MonthName] 
    FROM [dbo].[DutySavingFin] AS [Extent1] 
    LEFT OUTER JOIN [dbo].[MonthLookup] AS [Extent2] ON [Extent1].[Month] = [Extent2].[Month] 
ORDER BY [Extent1].[UserName] ASC, [Extent1].[FirstName] ASC 
+4

你能粘貼你的代碼嗎? – Guillaume86

+0

從直流在dataContext.UserTable 在dc.Month dataContext.MonthLookups加入m等於m.Month到SR 從X中sr.DefaultIfEmpty() 爲了通過dc.UserName,dc.FirstName 選擇新的{DC,SR .MothName}; – sugirthini

+0

請編輯你的問題,並使用代碼塊,將會更容易閱讀;) – Guillaume86

回答

1

上面的示例顯示了一個查詢。如果這是你的意思嵌套查詢不影響性能...

如果您正在使用大型數據集的工作:
1)確保你有DutySavingFin.Month,MonthLookup.Month索引和DutySavingFin.UserName + DutySavingFin.FirstName。
2)添加一個where子句來過濾掉你需要的記錄,除非你真的需要需要所有數據

+0

對嵌套查詢和普通的一個select查詢對大數據有性能影響。 – sugirthini

+0

我從來沒有看到有影響。查看L2S生成的查詢的執行計劃,然後嘗試在沒有子查詢的情況下平鋪相同的查詢。在正常情況下,SQL優化器將生成相同的執行計劃。 – KristoferA