1

SQL クエリ (実行計画コスト = 0.0127553)

SELECT 
 SUM(DATEDIFF(second, DTActivate, DTDeActivate)) AS Seconds,
 AA.ID AS AAID,
 AA.WorkStation
FROM 
 DbLogItems I 
INNER JOIN DbApplicationArguments AA ON 
 AA.Id = I.ApplicationArgument_ID
GROUP BY
 AA.ID,
 AA.WorkStation

C#

var q = from items in db.LogItem

 join aa in db.ApplicationArguments on 
  items.ApplicationArgument.ID equals aa.ID 
 into aaGroup

 from aaJoin in aaGroup.DefaultIfEmpty()

 group items by new 
 {
  aaJoin.ID,
  aaJoin.WorkStation
 } into grouping

 select new 
 {
  Seconds = grouping.Sum(x => SqlFunctions.DateDiff("second", x.DTActivate, x.DTDeActivate)),
  grouping.Key.ID,
  grouping.Key.WorkStation
};

結果の SQL が非常に大きい (実行計画コスト = 0.0199849)

SELECT 
 1 AS [C1], 
 [GroupBy1].[A1] AS [C2], 
 [GroupBy1].[K1] AS [ID], 
 [GroupBy1].[K2] AS [WorkStation] 
FROM 
(
 SELECT 
  [Join1].[K1] AS [K1], 
  [Join1].[K2] AS [K2], 
  SUM([Join1].[A1]) AS [A1] 
  FROM 
  ( 
   SELECT 
    [Extent2].[ID] AS [K1], 
    [Extent2].[WorkStation] AS [K2], 
    DATEDIFF(second, [Extent1].[DTActivate], [Extent1].[DTDeActivate]) AS [A1] 
   FROM 
    [dbo].[DbLogItems] AS [Extent1] 
   LEFT OUTER JOIN [dbo].[DbApplicationArguments] AS [Extent2] 
    ON [Extent1].[ApplicationArgument_ID] = [Extent2].[ID] 
  ) AS [Join1] 
 GROUP BY 
  [K1], 
  [K2] 
) AS [GroupBy1]

正しいlinqコードを書いてください。
私の SQL 実行計画のコスト = 0.0127553。
Linq SQL 実行計画コスト = 0.0199849。
DIFF = 21+10 レコードで 0,0072296

4

1 に答える 1

1

LINQ to SQL クエリはそのままです。より良い SQL を発行できない場合があります。DataContextただし、単純な古い T-SQL を記述して、さまざまな方法で呼び出すことができます。たとえば、カスタマイズしたテーブル値の UDFがIQueryable.

于 2012-06-12T00:57:15.430 に答える