Sql很快但转换为linq时速度很慢

时间:2015-10-07 18:24:44

标签: c# sql sql-server linq

这很快

SELECT Foo,
       count(*)
FROM
  (SELECT Foo
   FROM MyTable
   GROUP BY Foo,
            Bar,
            Baz) AS Subquery
GROUP BY Foo

这很快

var query = from fooGrp in
    (from rv in _myRepository.AsQueryable()
        group rv by new {rv.Foo, rv.Bar, rv.Baz}
        into grp
        select grp)
    group fooGrp by fooGrp.Key.Foo
    into grp2
    select new {grp2.Key, Count = grp2.Count()};
query.ToDictionary(x => x.Key, x => x.Count);

这很慢,真的很慢!

_myRepository.AsQueryable()
    .GroupBy(x => new { x.Foo, x.Bar, x.Baz })
    .GroupBy(x => x.Key.Foo)
    .ToDictionary(x => x.Key, x => x.Count());

我不明白:( 两个linq表达式有什么区别?它们都返回预期的结果集。

第一个表达式(快速)生成的SQL是:

SELECT 
    1 AS [C1], 
    [GroupBy1].[K1] AS [Foo], 
    [GroupBy1].[A1] AS [C2]
    FROM ( SELECT 
        [Distinct1].[Foo] AS [K1], 
        COUNT(1) AS [A1]
        FROM ( SELECT DISTINCT 
            [Extent1].[Foo] AS [Foo], 
            [Extent1].[Bar] AS [Bar], 
            [Extent1].[Baz] AS [Baz]
            FROM [dbo].[MyTable] AS [Extent1]
        )  AS [Distinct1]
        GROUP BY [Distinct1].[Foo]
    )  AS [GroupBy1]

第二个表达式生成的SQL(慢)是:

  

超过此帖子的字符数限制,所以不能发布:/

1 个答案:

答案 0 :(得分:0)

事实证明,LINQ表达式并不相同。

正确的linq表达式是:

_myRepository.AsQueryable()
    .GroupBy(x => new {x.Foo, x.Bar, x.Baz})
    .GroupBy(x => x.Key.Foo)
    .Select(x => new {x.Key, Count = x.Count()})
    .ToDictionary(x => x.Key, x => x.Count);

我缺少一个select,我没想到,因为在普通的SQL中你只能选择group by子句中的列。但是LINQ会做各种魔术来包含其余的列,除非你在select中限制它。