使用 LINQ 和经典 asp 的性能差异 sql 查询

performance difference sql query with LINQ and classic asp

我正在开发一个 asp.net 网络表单 4.5 网站, 我遇到了一个问题,我必须执行 sql 查询 来自 sql 最初由经典 asp.

编写的服务器

原来的查询是这样的..

select trait1, trait2, sum(qty) as qty from table2
right outer join table1 on (table1.col == table2.col)
where table2.idx is null 
group by trait1, trait2
order by trait1, trait2

并且在编写 .net 程序时,我正在尝试重写此查询... 就像这样

var myHashSet = new HashSet<string>(table2.Select(c => c.col));

from item in table2
where !myHashSet.Contains(item.col)
group item.qty by new {item.trait1, item.trait2} into total
select new
{
    trait1 = total.Key.trait1,
    trait2 = total.Key.trait2,
    qty = total.Sum()
} into anon
order by anon.qty descending
select anon

ps : 按部分忽略顺序..这不重要

对于经典 asp,大约需要 1.5 秒,但对于 c# asp.net, 大约需要 8 秒。

查询不完全一样,但它与我写的几乎相似。

我不明白为什么要花这么长时间.. 谁能告诉我为什么要花这么长时间以及我应该如何解决它?

您不需要哈希集,而是使用连接,您的查询可能看起来像

var inner = from two in table2
            join one in table1
                on two.col equals one.col
            group two by new
            {
                two.trait1,
                two.trait2
            } into total
            select new
            {
                total.Key.trait1,
                total.Key.trait2,
                qty = total.Sum(p => p.qty)
            };

编辑 为了完整起见,我还添加了一个左连接变体

var left = from two in table2
            from one in 
            (
                from temp in table1
                where temp.col == two.col
                select temp
            ).DefaultIfEmpty()
            group two by new
            {
                two.trait1,
                two.trait2
            } into total
            select new
            {
                total.Key.trait1,
                total.Key.trait2,
                qty = total.Sum(p => p.qty)
            };